i am trying to prototype the String Object to have a replaceWith Function that make me able to replace directly without using regular expression
String.prototype.replaceWith = function(f, t) {
var regExp = new RegExp("[" + f + "]", "g");
return this.replace(regExp, t);
};
when i tested my code in this string {{Hello}} for example i found that replacing double curly braces is a problem
Test
'{{Hello}}'.replaceWith('{{','<<').replaceWith('}}','>>');
Result is
"<<<<Hello>>>>"
when it should be
"<<Hello>>"
what is wrong with my script ??
thanks for your help
[{{]is the exact same as[{]which is the same as just{in regex. The square brackets indicate a character class which matches one of any characters within that class. You should just change:To:
So you have:
Which as Marlin pointed out has the same functionality as
String.prototype.replaceexcept you don’t need to add thegmodifier, and in my mind'{{Hello}}'.replace(/{{/g, '<<');is more concise and understandable to other coders than'{{Hello}}'.replaceWith('{{', '<<');.