8

given:

var regexp = new RegExp("<~~include(.*?)~~>", "g");

What's the easist way in javascript to assign a variable to whatever's matched by .*?

I can do this, but it's a little ugly:

myString.match(regexp).replace("<~~include", "").replace("~~>", "");
0

3 Answers 3

8

JavaScript should return an array object on a regex match, where the zero index of the array is the whole string that was matched, and the following indexes are the capture groups. In your case, something like:

var myVar = regexp.exec(myString)[1];

Should assign the value of the (.*?) capture group to myVar.

Sign up to request clarification or add additional context in comments.

1 Comment

Won't this throw an error if there is no match? It returns null if there's no match so attempting to access the array index of a null object would throw an error.
6

(Quotes from MDC)

Including parentheses in a regular expression pattern causes the corresponding submatch to be remembered. For example, /a(b)c/ matches the characters 'abc' and remembers 'b'.

Since .*? is the first (and only) remembered match, use $1 in your replacement string:

var foo = myString.replace(regexp, '$1');

Edit: As per your comment, you can also (perhaps with clearer intention) do this:

var foo = regexp.exec(myString)[1];

2 Comments

Thanks bears. Thing is, I don't actually want to replace the whole thing, I just want to find out what the value of .*? is.
Nick just commented (and then deleted his comment) that the first version will also work. He's correct, but I guess the intention of the replace version is less clear than the intention of the exec version. In either case, you have to assign the value returned by replace/exec to another variable.
0

You can use lookahead for part of this regular expression. See here:

Regular expression for extracting a number

and/or here:

http://www.regular-expressions.info/lookaround.html

3 Comments

Lookaround is not the answer. How is that supposed to help?
[quote] Thanks bears. Thing is, I don't actually want to replace the whole thing, I just want to find out what the value of .*? is. – morgancodes 15 mins ago
So they could write a regex that Edit matches <~~include(.*?)~~> and excludes the information they do not want.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.