DEV Community

Cover image for How to Replace All String Occurrences in JavaScript
learninglead
learninglead

Posted on

How to Replace All String Occurrences in JavaScript

To replace all string occurrences in JavaScript, use String.replace() method.

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

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.

Note that If the pattern is a string, only the first match will be replaced.

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

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

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

So how can we replace all the matches?

Using regular expression(RegEx), we can remove all the matches.

const str = "duck duck go";
const regEx = /duck/;
const result = str.replace(regEx, 'dove');
console.log(result); // πŸ‘‰οΈ dove dove go
Enter fullscreen mode Exit fullscreen mode

Here, 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.

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

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

Also, by adding the i flag, you can make** case insensitive replacements**.

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

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

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

const str = "duck@duck#go";
const regEx = /[^a-zA-Z0-9]/g;
const result = str.replace(regEx,' ');

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

In conclusion, we can easily replace all string occurrences, but I suggest using String.replace() method.

Top comments (0)