使用变量时,在Regex中转义方括号?

时间:2022-02-08 21:46:23

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

line var re = new RegExp(“[”+ j +“]”,'g');不起作用,因为我认为括号没有被转义。有谁知道如何逃脱它们,但仍然能够在模式中有一个变量?谢谢! :)

1 个解决方案

#1


10  

You should escape it with backslashes:

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

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

#1


10  

You should escape it with backslashes:

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

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