How to Replace all Occurrences of a String in JavaScript
In this tutorial, we’ll learn how to replace all occurrences of a string in JavaScript using String.replace()
method. We will also look at String.split()
and Array.join()
approach.
Using String.replace
Let’s take a quick look on the syntax:
const newStr = String.replace("pattern", "replacement");
The String.replace()
method returns a new string after replacing the occurrences of matched pattern
by replacement
string.
Pattern can be String or RegEx
Important point to note that the pattern
can be a String
or a RegEx
.
- If
pattern
isString
, then only the first occurrence is replaced. - If
pattern
isRegEx
, then all the occurrence are replaced if global flag/g
is used. You can also enable the case insensitive replacement by using/i
flag.
Let’s look at the example,
const lyrics = "Smelly cat, smelly cat what are they feeding you?";
console.log(lyrics.replace("cat", "kitty")); //pattern is String
console.log(lyrics.replace(/cat/, "kitty")); //pattern is RegEx
Output
"Smelly kitty, smelly cat what are they feeding you?"
"Smelly kitty, smelly cat what are they feeding you?"
We see that pattern as String
or RegEx
both returned the same result and replaced only first occurrence.
RegEx with global flag /g
Let’s use the RegEx
with global flag /g
to replace all the occurrences.
const lyrics = "Smelly cat, smelly cat what are they feeding you?";
console.log(lyrics.replace(/cat/g, "kitty"));
Output
"Smelly kitty, smelly kitty what are they feeding you?"
RegEx with case insensitive flag /i
Please note that above replacements are case sensitive, If we try this:
const lyrics = "Smelly cat, smelly cat what are they feeding you?";
console.log(lyrics.replace(/Smelly cat/g, "Sweet kitty"));
Output
"Sweet kitty, smelly cat what are they feeding you?"
We see that only first occurrence is replaced. We can enable case insensitive replacement by using /i
flag in RegEx
.
const lyrics = "Smelly cat, smelly cat what are they feeding you?";
console.log(lyrics.replace(/Smelly cat/gi, "Sweet kitty"));
Output
"Sweet kitty, Sweet kitty what are they feeding you?"
Yay! We are able to replace all occurrences of a string using Regex
with global and case insensitive flag /<pattern>/gi
Using String.split and Array.join
An alternative approach which is slower as compare to String.replace()
is two step approach:-
- Split the string using
String.split()
to remove the occurrence of matched (case sensitive) pattern and returns array, - Join the array again using
Array.join()
with replacement string
const newStr = String.split("pattern").join("replacement");
Let’s look at the example.
const lyrics = "Smelly cat, smelly cat what are they feeding you?";
console.log(lyrics.split("cat").join("kitty"));
Output
"Smelly kitty, smelly kitty what are they feeding you?"