Regex square brackets when using variable?

I have this code to replace all opening and closing square brackets that have a corresponding variable inside:

for (var j = 0; j <= temp.length; j++) { var re = new RegExp("["+j+"]", 'g'); imgData = imgData.replace(re, temp[j]); } 

String var re = new RegExp("["+j+"]", 'g'); does not work because I assume that the brackets are not escaped. Does anyone know how I would have escaped from them, but still could have a variable in the template? Thank you :)

+4
source share
1 answer

You should avoid it with backslashes:

 var re = new RegExp("\\[" + j + "\\]", "g"); 
+9
source

All Articles