Replace All String Occurrences in JavaScript

In this post, we’ll learn how to replace all string occurrences in JavaScript using the replace() and replaceAll() method.

1. Using the replace() method

The replace() method returns a new string with one, some, or all matches of a pattern replaced by a replacement. 

The replace() method takes two arguments: the pattern to be replaced and the string to replace it with.

The pattern can be a string or a regular expression (RegExp), and the replacement can be a string or a function called for each match. 

⚠️ If the pattern is a string, only the first match will be replaced. 

JavaScript
const str = "duck duck go";
const result = str.replace('duck', 'dove');

console.log(result); // πŸ‘‰οΈ dove duck go

As you can see, the replace() method replaced only the first match.

If you want to replace all matches, use a regular expression (RegExp).

JavaScript
const str = "duck duck go";
const regEx = /duck/g;
const result = str.replace(regEx, 'dove');

console.log(result); // πŸ‘‰οΈ dove dove go

We used regex pattern matching to replace all strings.

Note that we append the g (global) flag to the regex pattern, which means global.

If the g flag is not appended, it replaces only the first occurrence.

JavaScript
const str = "duck duck go";
const regEx = /duck/;
const result = str.replace(regEx, 'dove');

console.log(result); // πŸ‘‰οΈ dove duck go

⚠️ The replace() method is case-sensitive, so it won’t replace words that are capitalized differently.

JavaScript
const str = "Duck duck go";
const regEx = /duck/g;
const result = str.replace(regEx, 'dove');

console.log(result); // πŸ‘‰οΈ Duck dove go

To perform case-insensitive replacements use the i flag.

JavaScript
const str = "Duck duck go";
const regEx = /duck/gi;
const result = str.replace(regEx, 'dove');

console.log(result); // πŸ‘‰οΈ dove dove go

You can also use regex to remove all special characters from the string.


2. Using the replaceAll() method

The replaceAll() method returns a new string with all matches of a pattern replaced by a replacement.

It accepts two parameters: the pattern to be replaced and the string to replace it with.

The pattern can be a string or a RegExp.

JavaScript
const str = "duck duck go";
const result = str.replaceAll('duck', 'dove');

console.log(result); // πŸ‘‰οΈ dove dove go

⚠️ The method is currently supported only in browsers, and you might require a polyfill.


Conclusion

In conclusion, we explored two methods that can replace all occurrences of a specific string. You can use any method according to your need.


Learn More:

Unlock your programming potential with Stack Thrive! Discover step-by-step tutorials, insightful tips, and expert advice that will sharpen your coding skills and broaden your knowledge.

Leave a Comment

Facebook Twitter WhatsApp