4

I have been stuck on this silly issue for hours now. I know it seems stupid but I really don't know what I am missing. Any help would be appreciated.

Here's my issue:

var objReg = /touch/g;
var str = "abc touch def touch";
var arr = objReg.exec(str);

Here I expect the array arr to contain 2 elements but it only contains the 1st element even though I made sure to put the g modifier.

Can anyone guide me what is to be done here?

Debug: As shown in the image below, the array has just 1 element(index=0)

enter image description here

Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
ManJoey
  • 213
  • 2
  • 7
  • 2
    You have to repeat `RegExp.exec` until the returned value is `null`. Alternatively, you can use `str.match(re)`, which returns just the array of matches. – Marko Gresak Nov 01 '17 at 17:36

2 Answers2

7

To get the effect you want, you need to do the matching with String.prototype.match():

var arr = str.match(objReg);

The RegExp .exec() function does not behave the same way with regards to the g flag. The flag does do something with .exec() but not what .match() does.

Pointy
  • 405,095
  • 59
  • 585
  • 614
  • I can't thank you enough, sir. This solved my problem :'). Will accept the answer as soon as I am able to – ManJoey Nov 01 '17 at 17:40
6

The g modifier causes the regex object to maintain state. It tracks the index after the last match. If you wanted to use .exec(), you can use a loop, and it will automatically start searching the string at the appropriate point.

var objReg = /touch/g;
var str = "abc touch def touch";
var match = null;
var arr = [];

console.log(objReg.lastIndex);

while ((match = objReg.exec(str))) {
  arr.push(match[0]);
  console.log(objReg.lastIndex);
}

console.log(objReg.lastIndex);

console.log(arr);
llama
  • 2,535
  • 12
  • 11