I think you try to achieve too much at once. If you have a large pattern with a LOT of alternations with the vertical bar/pipe |
your pattern gets slow because the regex engine has to backtrack a lot.
Therefore, I suggest to chain-replace instead.
Here are two ReplaceAll candidates to play with:
//Regular Expression Based Implementation
String.prototype.replaceAll = function(search, replacement) {
var target = this;
return target.replace(new RegExp(search, 'g'), replacement);
};
//Split and Join (Functional) Implementation
String.prototype.replaceAll2 = function(search, replacement) {
var target = this;
return target.split(search).join(replacement);
};
var t0 = performance.now();
//your Approach
var t1 = performance.now();
console.log("Call to doSomething took " + (t1 - t0) + " milliseconds.")
var t0 = performance.now();
str.replaceAll('Erica', 'Example');
//...
var t1 = performance.now();
console.log("Call to doSomething took " + (t1 - t0) + " milliseconds.")
var t0 = performance.now();
str.replaceAll2('Erica', 'Example');
//...
var t1 = performance.now();