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)
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With