使用全局属性时,JavaScript正则表达式速度较慢
我试图替换一些html字符串中括号中的字符串。当我使用常规替换时,速度很快,当我尝试为全局替换创建模式时,它最终抛出堆栈溢出错误。它似乎在进程路径的某个地方,将单个字符串转换为一个字符数组。 有什么想法吗使用全局属性时,JavaScript正则表达式速度较慢,javascript,regex,performance,Javascript,Regex,Performance,我试图替换一些html字符串中括号中的字符串。当我使用常规替换时,速度很快,当我尝试为全局替换创建模式时,它最终抛出堆栈溢出错误。它似乎在进程路径的某个地方,将单个字符串转换为一个字符数组。 有什么想法吗 var o = { bob : 'is cool', steve : 'is not' }; for (n in o) { /* pattern = new RegExp('\[' + n.toUpperCase() + '\]', 'g'); retString = retSt
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]/
)
看看这一点在起作用
要证明差异,请执行以下操作:
pattern = new RegExp('\[' + n.toUpperCase() + '\]', 'g');
alert(pattern); // /[BOB]/g
pattern2 = new RegExp('\\[' + n.toUpperCase() + '\\]', 'g');
alert(pattern2); // /\[BOB\]/g
你的
o
变量是什么样子的?{鲍勃:“很酷”,史蒂夫:“不是”}等等……就是这样!多谢各位@佩普金:哈哈,谢谢。我不喜欢在我自己的答案上贴出来,因为我不想看起来像是在问分数,但这是他的第一个问题,我想他不知道接受答案。哈哈,对不起!是的,这是我第一次发帖,我还在学习这个网站的工作原理。再次感谢你的回答,太完美了。
pattern = new RegExp('\[' + n.toUpperCase() + '\]', 'g');
alert(pattern); // /[BOB]/g
pattern2 = new RegExp('\\[' + n.toUpperCase() + '\\]', 'g');
alert(pattern2); // /\[BOB\]/g