Very hard scripting question - Why I can't reuse function? Is it bug?

  • 1
  • Question
  • Updated 2 years ago
var str = "test, test, test, s";
var regex = new RegExp("[, ]","g");

var indexesToRemove = getAllIndexesOf(str, regex);
var substringPositionsArr = getAllIndexesOf(str, regex);

function getAllIndexesOf(str, regex) {
       var counts = [], m;
       while (m = regex.exec(str)) {
           counts.push(regex.lastIndex - m[0].length);
       }
       return counts;
   }

alert(indexesToRemove);
alert(substringPositionsArr);
This is my code. I am calling exactly same function with same parameters. But I must create new regex for every single function calling. Otherwise is my array empty. Why? This code works in Chrome without problems.
Photo of Jaroslav Bereza

Jaroslav Bereza

  • 761 Posts
  • 149 Reply Likes
  • confused

Posted 2 years ago

  • 1
Photo of Max Johnson

Max Johnson, Champion

  • 399 Posts
  • 171 Reply Likes
Long story short, after the exec function, the regex fails to reset it's lastIndex. Reset it manually before the while and it works again.

var str = "test, test, test, s";
var regex = new RegExp("[, ]","g");

var indexesToRemove = getAllIndexesOf(str, regex);
var substringPositionsArr = getAllIndexesOf(str, regex);

function getAllIndexesOf(str, regex) {
var counts = [], m;
regex.lastIndex = 0;
while (m = regex.exec(str)) {
counts.push(regex.lastIndex - m[0].length);
}
return counts;
}

alert(indexesToRemove);
alert(substringPositionsArr);