[JavaScript] Resolve issue on cannot use `replaceAll()`

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.

About C.H. Ling 260 Articles
a .net / Java developer from Hong Kong and currently located in United Kingdom. Thanks for Google because it solve many technical problems so I build this blog as return. Besides coding and trying advance technology, hiking and traveling is other favorite to me, so I will write down something what I see and what I feel during it. Happy reading!!!

Be the first to comment

Leave a Reply

Your email address will not be published.


*


This site uses Akismet to reduce spam. Learn how your comment data is processed.