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.
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).
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.
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.
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.
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.
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:
- Pad a Number with Leading Zeros in JavaScript
- Unexpected identifier Error in JavaScript
- Dynamically Access Object Property Using Variable in JavaScript
- Check if a Key exists in an Object in JavaScript
- Get the Last N Elements of an Array in JavaScript
- Calculate Percentage Between Two Numbers in JavaScript
- Remove Special Characters from a String in JavaScript
- Using async/await with a forEach loop
- Wait for all promises to resolve in JavaScript