Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript RegExp - g modifier not working

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

like image 810
ManJoey Avatar asked Dec 13 '22 20:12

ManJoey


2 Answers

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.

like image 127
Pointy Avatar answered Dec 29 '22 21:12

Pointy


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);
like image 40
llama Avatar answered Dec 29 '22 22:12

llama