String.replaceAll

Something that often catches out developers when doing string replacement in Javascript is that it is not global by default. That is, when replacing a substring, only the first instance is replaced:

const str = 'Welcome to WEBSITE. We hope you enjoy WEBSITE.';
console.log(str.replace('WEBSITE', 'newinweb.com'));
// 'Welcome to newinweb.com. We hope you enjoy WEBSITE.'

Previously, to replace all instances of WEBSITE above, you would need to create a Regex, and set the g flag to make it global.

const str = 'Welcome to WEBSITE. We hope you enjoy WEBSITE.';
const regex = new RegExp('WEBSITE', 'g');
console.log(str.replace(regex, 'newinweb.com'));
// 'Welcome to newinweb.com. We hope you enjoy newinweb.com.'

This works fine, but it makes the code a bit harder to read, and it’s also easy to forget to create this regex.

Chrome, Firefox and Safari all now support the replaceAll function on strings, meaning you no longer have to use a regex to replace multiple instances of a string:

const str = 'Welcome to WEBSITE. We hope you enjoy WEBSITE.';
console.log(str.replaceAll('WEBSITE', 'newinweb.com'));
// 'Welcome to newinweb.com. We hope you enjoy newinweb.com.'

Simple, but very useful!

Other recent posts: