Skip to content

Replace all instances of a string in JavaScript

Learn how to replace all occurrences of a string in a string with JavaScript and regular expressions.

Replacing one match

To replace one instance of a word in a string, we use replace() method. This replaces only the first match.

const str = 'We poop code. Do you poop code?';
const newStr = str.replace('poop', 'shit');
console.log(newStr); // We shit code. Do you poop code?
Advertisements

We can also use Regular Expressions to achieve this.

const str = 'We poop code. Do you poop code?';
const newStr = str.replace('/poop/', 'shit');

//or const newStr = myMessage.replace(new RegExp('poop'), 'shit');

console.log(newStr); // We shit code. Do you poop code?

Replacing all matches

to replace all instances of the specified string, we need to use a regular expression as the first argument of the replace method along with a global flag ‘g’.

This ‘g’ flag specifies that find and replace will be done globally.

Note: This is a case-sensitive find and replace.

const str = 'We poop code. Do you poop code?';
const newStr = str.replace('/poop/g', 'shit');
//or
const newStr = str.replace(new RegExp('poop','g'), 'shit');

console.log(newStr); // We shit code. Do you shit code?
Advertisements

To make it case-insensitive, you can pass an additional flag ‘i’ along with ‘g’

const str = 'We Poop code. Do you poop code?';
const newStr = str.replace('/poop/gi', 'shit');
//or
const newStr = str.replace(new RegExp('poop','gi'), 'shit');

console.log(newStr); // We shit code. Do you shit code?

There’s another way to replace all occurences of a string in a string using split() and join(), but that is performance critical. I advise you avoid using split() and join().

, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,

Leave a Reply

Your email address will not be published.

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