FAQ
overflow

Great Answers to
Questions About Everything

QUESTION

I think I must just be really tired, because this should be really simple, but it's just not working for me. I want to match a portion of a string using a regex and then access that parenthesized substring.

var myString = "something format_abc"; // I want "abc"

var arr = /(?:^|\s)format_(.*?)(?:\s|$)/(myString);

console.log(arr);     // prints: [" format_abc", "abc"] .. so far so good.
console.log(arr[1]);  // prints: undefined  (???)
console.log(arr[0]);  // prints: format_undefined (!!!)

can anyone see what I'm doing wrong?


Update: I've discovered that there was nothing wrong with the regex code above: the actual string which I was testing against was this:

"date format_%A"

Reporting that "%A" is undefined seems a very strange behaviour, but not directly related to this question, so I've opened a new one here. Thanks to everyone who responded.


Update: The issue was that console.log takes its parameters like a printf statement, and since the string I was logging ("%A") had a special value, it was trying to find the value of the next parameter.

Since this was just a silly bug on my part, I'll now close this question.

{ asked by nickf }

ANSWER

You can access capturing groups like this:

var myString = "something format_abc";
var myRegexp = /(?:^|\s)format_(.*?)(?:\s|$)/g;
var match = myRegexp.exec(myString);
alert(match[1]);  // abc

And if there are multiple matches you can iterate over them:

match = myregexp.exec(myString);
while (match != null) {
    // matched text: match[0]
    // match start: match.index
    // capturing group n: match[n]
}

{ answered by CMS }
Tweet