Java String.replace vs Javascript String.prototype.replace
Java String.replace replaces all occurrences of a given string with the replacement string.
JS String.prototype.replace replaces only the first occurrence if the pattern is a string.
Now before this proposal which became a part of ES12(2021), if we had to replace all occurrences of a given pattern with a replacement, we had to use the regex pattern as below.
const p = 'The quick brown fox jumps over the lazy Dog*. If the Dog* reacted, was it really lazy?';const regex = /Dog*/g;
console.log(p.replaceAll(regex, 'monkey'));Output-1: The quick brown fox jumps over the lazy monkey*. If the monkey* reacted, was it really lazy?const regexWithEscapedAserisk = /Dog\*/ig;
console.log(p.replaceAll(regex1, 'monkey'));Output-2: The quick brown fox jumps over the lazy monkey. If the monkey reacted, was it really lazy?
As you can see the first output, though our intention(assume) was to replace all occurrences of Dog* with monkey, in the output we still see aserisk after monkey.
If the pattern string itself contains any regex special characters, you should be extra careful to escape the special characters as in Output-2’s result.
From this, String.prototype.replaceAll is a part of nodejs from v15 and that makes it straightforward as in java where in we want to replace the exact occurence of a source string with a target string in all places.