简体   繁体   中英

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! :)

你应该用反斜杠来逃避它:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM