[英]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');
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");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.