开发者

Slow JavaScript Regex when using global attribute

I am trying to replace strings in brackets in some html string. When I use a regular replace, its fast, when I try to create a pattern for global replace, it ends up throwing a stack overflow error. It seems like somewhere along the process path, it converts my single string to an array of characters. Any ideas?

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());
}


You need to escape your slash when you're building your regular expression (because you want the expression to have an escaped bracket; as it is now, your expression compiles to /[BOB]/ or /[STEVE]/, which defines a character class!)

for (n in o) {
  pattern = new RegExp('\\[' + n.toUpperCase() + '\\]', 'g');
  retString = retString.replace(pattern, o[n].toString());
}

See http://jsfiddle.net/GvdHC/ to see this in action.

To demonstrate the difference:

pattern = new RegExp('\[' + n.toUpperCase() + '\]', 'g');
alert(pattern);  // /[BOB]/g
pattern2 = new RegExp('\\[' + n.toUpperCase() + '\\]', 'g');
alert(pattern2); // /\[BOB\]/g
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜