JavaScript – Replace all Occurrences of a Substring in String
To replace all occurrences of a substring in a string with a new value in JavaScript, call replaceAll() method on this string, and pass the search string and replacement string as arguments.
Syntax
The syntax to replace all occurrences of a substring searchValue
with a new value replaceValue
in this string str
is
str.replaceAll(searchValue, replaceValue)
replaceAll() method returns a new string with the replacements done, and keeps the original string str
unchanged.
Examples
In the following example, we take three strings: str, searchValue, and replaceValue. We will use replaceAll() method to replace all the occurrence of searchValue with replaceValue in str.
index.html
Conclusion
In this JavaScript Tutorial, we learned how to replace all the occurrences of a substring with a new value in this string in JavaScript, using replaceAll() method, with examples.