Asked : Nov 17
Viewed : 27 times
I have this string in my JavaScript code:
"Test abc test test abc test test test abc test test abc"
Doing:
str = str.replace('abc', '');
Seems to only remove the first occurrence of abc
in the string above.
How can I replace all occurrences of it?
Nov 17
Update: In the latest versions of most popular browsers, you can use replaceAll
as shown here:
let result = "1 abc 2 abc 3".replaceAll("abc", "xyz");
// `result` is "1 xyz 2 xyz 3"
But check Can I use or another compatibility table first to make sure the browsers you're targeting have added support for it first.
answered Dec 31
1. Splitting and joining an array
If you google how to "replace all string occurrences in JavaScript", most likely the first approach you'd find is to use an intermediate array.
Example 1:
const search = ' ';
const replaceWith = '-';
const result = 'duck duck go'.split(search).join(replaceWith);
result; // => 'duck-duck-go'
Example 2:
function replaceAll(string, search, replace) {
return string.split(search).join(replace);
}
replaceAll('abba', 'a', 'i'); // => 'ibbi'
replaceAll('go go go!', 'go', 'move'); // => 'move move move!'
replaceAll('oops', 'z', 'y'); // => 'oops'
This approach requires transforming the string into an array, and then back into a string. Let's continue looking for better alternatives.
2. replace() with a global regular expression
The string method string.replace(regExpSearch, replaceWith)
searches and replaces the occurrences of the regular expression regExpSearch
with replaceWith
string.
Example 1:
const searchRegExp = /\s/g;
const replaceWith = '-';
const result = 'duck duck go'.replace(searchRegExp, replaceWith);
result; // => 'duck-duck-go'
3. replaceAll() method
Finally, the method string.replaceAll(search, replaceWith)
replaces all appearances of search
string with replaceWith
.
Let's replace all occurrences of ' '
with '-'
:
const search = ' ';
const replaceWith = '-';
const result = 'duck duck go'.replaceAll(search, replaceWith);
result; // => 'duck-duck-go'
answered Dec 31
Replace all occurrences of a string in JavaScript
Example 1:
const str = 'old old world';
const replacedAll = str.replace(/old/g, 'new');
console.log(replacedAll);
Example 2 :
const str = 'old old world';
const replacedAll = str.replaceAll('old', 'new');
console.log(replacedAll);
There is no good reason to use replaceAll
over replace
in this scenario.
answered Dec 31