Reputation: 15
Is there any way to specify which group I want stored without the use of Pattern or Matcher? The following code matches the "hello", I'd like to match the "hi" in the second group.
var matches = [];
var test = "#hello# #hello#hi# #hello# #hi#";
test.replace(/#(hello)#(hi)#/gi, function (string, match) {
matches.push(match);
});
alert(matches);
Pretty sure I need a $2 or a .group(1) somewhere.
edit: function(match, $1, $2) did it.
Upvotes: 1
Views: 371
Reputation: 6753
You need to store the second-captured group (hi
) in the matches
array by using a reference to the second captured group:
var matches = [];
var test = "#hello# #hello#hi# #hello# #hi#";
test.replace(/#(hello)#(hi)#/gi, function(match, $1, $2){
matches.push($2); // match = "#(hello)#(hi)#", $1 = hello, $2 = hi
});
alert(matches); // ["hi"]
Upvotes: 2
Reputation: 784958
Remove g
switch and use String#match
:
"#hello# #hello#hi# #hello# #hi#".match(/#(hello)#(hi)#/i);
//=> ["#hello#hi#", "hello", "hi"]
Upvotes: 0