我正在尝试替换某些 html 字符串中括号中的字符串。当我使用常规替换时,速度很快,当我尝试创建全局替换模式时,它最终会抛出堆栈溢出错误。似乎在进程路径的某个地方,它将我的单个字符串转换为字符数组。 有什么想法吗?
var o = { bob : 'is cool', steve : 'is not' };
for (n in o) {
/*
pattern = new RegExp('\[' + n.toUpperCase() + '\]', 'g');
retString = retString.replace(pattern, o[n].toString());
*/
retString = retString.replace('[' + n.toUpperCase() + ']', o[n].toString());
}
最佳答案
在构建正则表达式时,您需要转义斜杠(因为您希望表达式有一个转义括号;就像现在一样,您的表达式编译为 /[BOB]/
或 /[STEVE]/
,定义字符类!)
for (n in o) {
pattern = new RegExp('\\[' + n.toUpperCase() + '\\]', 'g');
retString = retString.replace(pattern, o[n].toString());
}
参见http://jsfiddle.net/GvdHC/来看看它的实际效果。
为了演示差异:
pattern = new RegExp('\[' + n.toUpperCase() + '\]', 'g');
alert(pattern); // /[BOB]/g
pattern2 = new RegExp('\\[' + n.toUpperCase() + '\\]', 'g');
alert(pattern2); // /\[BOB\]/g
关于javascript - 使用全局属性时 JavaScript 正则表达式变慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3701766/