【问题标题】:Slow JavaScript Regex when using global attribute使用全局属性时 JavaScript 正则表达式速度慢
【发布时间】:2010-09-13 15:18:29
【问题描述】:

我正在尝试替换某些 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());
}

【问题讨论】:

  • 你的 o 变量是什么样的?
  • { bob : '很酷', steve : '不是' } 等等...

标签: javascript regex performance


【解决方案1】:

在构建正则表达式时,您需要转义斜杠(因为您希望表达式有一个转义括号;就像现在一样,您的表达式编译为 /[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

【讨论】:

  • 就是这样!非常感谢!
  • @pepkin 哈哈谢谢。我不喜欢在我自己的答案上发布,因为我不想看起来像是在要求积分,但这是他的第一个问题,我认为他不知道接受答案。
  • 哈哈对不起!是的,这是我第一次发帖,我还在学习这个网站的工作原理。再次感谢您的回答,非常完美。
猜你喜欢
  • 1970-01-01
  • 2013-03-16
  • 2013-11-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-25
  • 1970-01-01
相关资源
最近更新 更多