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("~~>", "");
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("~~>", "");
Share
Improve this question
edited Aug 4, 2010 at 20:26
Matt Ball
360k102 gold badges653 silver badges720 bronze badges
asked Aug 4, 2010 at 20:23
morgancodesmorgancodes
25.3k39 gold badges138 silver badges191 bronze badges
0
3 Answers
Reset to default 8JavaScript 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
.
(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];
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