", "g"); What an easy way i...">

Javascript - get only the variable part of a regular expression

Given:

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

What an easy way in javascript to assign a variable to any that matches. *?

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

 myString.match(regexp).replace("<~~include", "").replace("~~>", ""); 
+7
javascript regex
source share
3 answers

Javascript should return the array object to match the regular expression, where the zero index of the array is the entire string that has been matched, and the following indexes are capture groups. In your case, something like:

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

should assign a capture group value (.*?) to myVar .

+6
source share

(Quotes from MDC )

The inclusion of parentheses in the regular expression pattern brings to mind the corresponding subclause. For example, /a(b)c/ matches the characters 'abc' and remembers 'b' .

So how .*? is the first (and only) match to remember, use $1 in your replacement string:

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

Edit:. According to your comment, you can also (perhaps with a clearer intent):

 var foo = regexp.exec(myString)[1]; 
+6
source share

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

Regular expression to extract a number

and / or here:

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

0
source share

All Articles