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!)See http://jsfiddle.net/GvdHC/ to see this in action.
To demonstrate the difference: