1

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.

2 Answers 2

2

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"]
Sign up to request clarification or add additional context in comments.

Comments

0

Remove g switch and use String#match:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.