Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript -- get only the variable part of a regex match

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("~~>", "");
like image 505
morgancodes Avatar asked Aug 04 '10 20:08

morgancodes


2 Answers

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.

like image 178
eldarerathis Avatar answered Oct 08 '22 08:10

eldarerathis


(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];
like image 41
Matt Ball Avatar answered Oct 08 '22 07:10

Matt Ball