In JavaScript, replace()
only can update first item but not for all in string. replaceAll()
is a new method introduced to v8 engine. However, for some browser engine still cannot recognize it. To resolve this issue, it is require to use regex to handle it.
const p = 'The quick brown fox jumps over the lazy dog. If the dog reacted, was it really lazy?'; console.log(p.replaceAll('dog', 'monkey')); // expected output: "The quick brown fox jumps over the lazy monkey. If the monkey reacted, was it really lazy?" // global flag required when calling replaceAll with regex const regex = /Dog/ig; console.log(p.replaceAll(regex, 'ferret')); // expected output: "The quick brown fox jumps over the lazy ferret. If the ferret reacted, was it really lazy?" console.log(p.replace(/dog/g, 'gundam')) // expected output: "The quick brown fox jumps over the lazy gundam. If the gundam reacted, was it really lazy?"
As example above, it can use /g
as global replacement.
Leave a Reply