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("~~>", "");
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
.
(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];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With