1

I need to replace ALL occurrences of '|B' with '' I've tried using 'replace' which only replaces the first occurrence in a string, and both of the following ReplaceAll prototypes neither of which produce the desired result:

String.prototype.replaceAll = function(search, replacement) {
    var target = this;
    return target.replace(new RegExp(search, 'g'), replacement);
};

and

String.prototype.replaceAll = function(search, replacement) {
    var target = this;
    return target.split(search).join(replacement);
};

Any assistance is greatly appreciated!

Rani Radcliff
  • 4,856
  • 5
  • 33
  • 60

1 Answers1

1

When you create a RegExp from an expression, you could have characters that need to be escaped so they are not treated as RegExp. In your case, the | is a special character in regular expressions.

See Is there a RegExp.escape function in Javascript?

// Shamelessly copy/pasted from the link above
RegExp.escape = function(s) {
    return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
};

String.prototype.replaceAll = function(search, replacement) {
    return this.replace(new RegExp(RegExp.escape(search), 'g'), replacement);
};
Community
  • 1
  • 1
Ruan Mendes
  • 90,375
  • 31
  • 153
  • 217