Search code examples
javascriptregexfor-loopiteratorstring-concatenation

Javascript: new Regexp destroys for loop iterator when string is concatenated


I have an object called script. It contains a variable called name that contains a string.

There is also an array that contains multiple script objects, the array is called scripts. Its size is 5.

I have a for loop where I want to create a new RegExp for each name of the script objects concatenated with "(":

var scriptName;
for(var i=0; i<scripts.length; i++){
    console.log("i = "+i);
    scriptName = scripts[i].name+"(";
    var newRegex = new RegExp(scriptName, 'g');
}

The problem is that whenever I concatenate scripts[i].name with "(" the for loop stops working. Instead of incrementing i it stops at i=0. Which is weird because the for loop still stops instead of looping indefinitely.

If I replace

scriptName = scripts[i].name+"(";

with

scriptName = scripts[i].name;

I get the correct output:

0, 1, 2, 3, 4

Otherwise I get the output 0 x 5 times


Solution

  • You will need to escape the string before you build the RegExp - like so:

    var scriptName;
    for(var i=0; i<scripts.length; i++){
        console.log("i = "+i);
        scriptName = scripts[i].name+"(";
        // Escape for regex
        var escapedName = scriptName.replace(
            /[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"
        );
        var newRegex = new RegExp(escapedName, 'g');
    }
    

    The funny /[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g part matches the regexp special characters such as ^ + ( ) and then the replace adds slashes before them so that they are ignored when the string is parsed.