morgancodes
morgancodes

Reputation: 25265

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("~~>", "");

Upvotes: 8

Views: 14356

Answers (3)

eldarerathis
eldarerathis

Reputation: 36213

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.

Upvotes: 8

Matt Ball
Matt Ball

Reputation: 359956

(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];

Upvotes: 6

Skyler
Skyler

Reputation: 341

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

Upvotes: 0

Related Questions