0

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

There is also an array that contains multiptle 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 increamenting i it stops at i=0. Which is weird beacause the for loop still stops instead of looping indefinately.

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

Elias
  • 149
  • 1
  • 9

1 Answers1

1

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.

madebydavid
  • 6,457
  • 2
  • 21
  • 29