Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escaping square brackets in Regex when using a variable?

I have this code to replace all opening and closing square brackets which has a matching variable inside:

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

The line var re = new RegExp("["+j+"]", 'g'); doesn't work because I assume the brackets aren't being escaped. Does anyone know how I would escape them, but still be able to have a variable in the pattern? Thanks! :)

like image 841
Joey Morani Avatar asked Dec 20 '22 12:12

Joey Morani


1 Answers

You should escape it with backslashes:

var re = new RegExp("\\[" + j + "\\]", "g");
like image 164
VisioN Avatar answered Jan 17 '23 19:01

VisioN