Regex does not capture groups in javascript

I'm a little rusty in my regex and javascript. I have the following var line:

var subject = "javascript:loadNewsItemWithIndex(5, null);"; 

I want to extract 5 using regex. This is my regex:

 /(?:loadNewsItemWithIndex\()[0-9]+/) 

It is applied as follows:

 subject.match(/(?:loadNewsItemWithIndex\()[0-9]+/) 

Result:

 loadNewsItemWithIndex(5 

What is the cleanest, most readable way to extract 5 as a single line? Is it possible to do this by excluding loadNewsItemWithIndex( from the match, rather than matching 5 as a subgroup?

+7
source share
3 answers

The return value from String.match is an array of matches, so you can put parentheses around the part of the number and simply retrieve this match index (where the first match represents the entire consistent result, and the subsequent entries for each capture are a group):

 var subject = "javascript:loadNewsItemWithIndex(5, null);"; var result = subject.match(/loadNewsItemWithIndex\(([0-9]+)/); // ^ ^ added parens document.writeln(result[1]); // ^ retrieve second match (1 in 0-based indexing) 

Sample code: http://jsfiddle.net/LT62w/

Edit: Thanks to @Alan for fixing how non-conceptual matches work.

Actually, it works fine. Text matched inside a non-capturing group is still consumed, the same as text that matches outside of any group. A capture group is similar to a non-capture group with additional functionality: in addition to grouping, it allows you to retrieve everything that it matches regardless of the overall match.

+8
source

I believe the following regular expression should work for you:

 loadNewsItemWithIndex\(([0-9]+).*$ var test = new RegExp(/loadNewsItemWithIndex\(([0-9]+).*$/); test.exec('var subject = "javascript:loadNewsItemWithIndex(5, null);";'); 

Break this

 loadNewsItemWithIndex = exactly that \( = open parentheses ([0-9]+) = Capture the number .* = Anything after that number $ = end of the line 
+4
source

That should be enough:

 <script> var subject = "javascript:loadNewsItemWithIndex(5, null);"; number = subject.match(/[0-9]+/); alert(number); </script> 
+3
source

All Articles