Toady
Toady

Reputation: 15

Storing specific JS Regex captured groups in array?

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

Answers (2)

Gaurang Tandon
Gaurang Tandon

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

anubhava
anubhava

Reputation: 784958

Remove g switch and use String#match:

"#hello# #hello#hi# #hello# #hi#".match(/#(hello)#(hi)#/i);
//=> ["#hello#hi#", "hello", "hi"]

Upvotes: 0

Related Questions