How to Replace All Occurrences of a String in JavaScript
There are several ways we can approach replacing all occurrences of a string in JavaScript. In this tutorial, we will go through some of these approaches and how we can apply regular expressions to perform more complex string matches.
replaceAll() Method
The most simple way to replace all occurrences of a value in a string is with the replaceAll
method. The first parameter is the values to find and the second is what to replace them with.
let string = "The quick brown fox jumps over the lazy dog. The fox is a fast animal.";
string = string.replaceAll('fox', 'cat');
console.log(string);
The quick brown cat jumps over the lazy dog. The cat is a fast animal.
You can also use regular expressions for complex pattern matching. The example below uses regex to match any words containing ight
. All regex must be in global search mode (/g
) or an error will be thrown.
let string = "Some words: sight light right.";
string = string.replaceAll(/[^n]ight/g, 'foo');
console.log(string);
Some words: foo foo foo.
note - as of August 2020, the only the latest version of Firefox and Chrome (85) support replaceAll
. Chrome 85 is now available but consider that a lot of users will not have updated their browser yet.
Combine the split() and join() Methods
It is possible to replace all occurrences of a string by combining the split
and join
methods. The value to find goes in split
and what to replace it with goes in join
.
let string = "The quick brown fox jumps over the lazy dog. The fox is a fast animal.";
let search = "fox";
let replacement = "cat";
string = string.split(search).join(replacement);
console.log(string);
The quick brown cat jumps over the lazy dog. The cat is a fast animal.
In many cases, it would be cleaner to just put the values inside the methods, though in the above example I defined the search
and replacement
as variables to highlight which one goes where.
string = string.split("fox").join("cat");
replace method with regex
A clean way to replace all values in a string is with the JavaScript replace
method. Put the regular expression in the first argument and the value to replace the matches within the second.
let string = "The quick brown fox jumps over the lazy dog. The fox is a fast animal.";
string = string.replace(/fox/g, 'cat');
console.log(string);
The quick brown cat jumps over the lazy dog. The cat is a fast animal.
Conclusion
You now know a variety of ways to replace all occurrences of a string in JavaScript. It seems that replaceAll
is going to become a popular option in the future due to its simplicity and performance, though, it is going to be some months before it is safe to use in a production program.