BlueEyesWhiteDragon
BlueEyesWhiteDragon

Reputation: 427

Getting index of matched strings in Regex Expression

I am trying to get the index of a matched string from inside a for loop of values to match the string with...

Example:

var arr = ["foo", "bar"],
    arr2 = [];
for(var j=0;j<arr.length;j++){
    var str = "foo bar flub alien alcohol foo bar foo",
    re = new RegExp("("+arr[j]+")", "ig"),
    //method = str.match(re) || re.exec(str),
    obj = {match: method, index: method.index};
    arr2.push(obj);
    console.log(obj);
}

I am aware this currently doesn't work and I'm trying to work out which method to go with for this problem. Getting stuck every time, I have come to the Stack Overflow community to ask you, what am I doing wrong when I am trying to achieve the following (for the result of arr2):

[{string: "foo", index: 0}, 
 {string: "foo", index: 27}, 
 {string: "bar", index: 4},
 {string: "bar", index: 30}]

Upvotes: 1

Views: 164

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626845

You can use the following code:

var arr = ["foo", "bar"];
arr2 = [];
for(var j=0;j<arr.length;j++){
 var str = "foo bar flub alien alcohol foo bar foo";
 re = new RegExp(arr[j], "ig");
 while ((m = re.exec(str))!== null) {
   if (m.index === re.lastIndex) {
      re.lastIndex++;
   }
   obj = {match: m[0], index: m.index};
   arr2.push(obj);
   console.log(obj);
 }
}

I changed:

  • The regex definition (removed unnecessary capturing group)
  • Used exec to get access to multiple matches.

The m.index is the * 0-based index of the match in the string.* (MDN) I access Group 0 with m[0] to get the whole text that matched since there are no capturing groups set (no unescaped round brackets in the pattern).

Upvotes: 1

Oriol
Oriol

Reputation: 288120

Since you are using global regex, you should keep calling exec until there is no match. You can do this with a while loop.

var arr = ["foo", "bar"],
    arr2 = [],
    str = "foo bar flub alien alcohol foo bar foo";
for(var j=0; j<arr.length; j++) {
    var re = new RegExp(arr[j], "ig"),
        match;
    while(match = re.exec(str))
        arr2.push({string: match[0], index: match.index});
}

Upvotes: 0

Related Questions