views:

30

answers:

1

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());
}
+2  A: 

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
Daniel Vandersluis
That was it! Thank you very much!
Andrew Maurer
@Andrew if this solved your problem, press the checkmark beside the answer to accept it.
Daniel Vandersluis
Too late, he's gone :D But you have 10 points from me ;)
pepkin88
@pepkin Haha thanks. I don't like posting that on my own answers because I don't want to look like I'm asking for points, but it was his first question and I assumed he didn't know about accepting answers.
Daniel Vandersluis
@Daniel - HAHA sorry! Yes this was my first time posting and I'm still learning how this site works. Thanks again for the answer, it was perfect.
Andrew Maurer