JavaScript – Replace a Substring in String

To replace the occurrence(s) of a substring in a string with a new value in JavaScript, call replace() method on this string, and pass the search string and replacement string as arguments.

Syntax

The syntax to replace a substring searchValue with a new value replaceValue in this string str is

str.replace(searchValue, replaceValue)

replace() method returns a new string with the replacement(s) done, and keeps the original string str unchanged.

ADVERTISEMENT

Examples

Replace the First Occurrence

In the following example, we take three strings: str, searchValue, and replaceValue. We will use replace() method to replace the first occurrence of searchValue with replaceValue in str.

index.html

Replace All Occurrences using Global Modifier

In the following example, we take a string str and replace ‘apple’ with ‘mango’ at all the occurrences using global(g) modifier.

index.html

Conclusion

In this JavaScript Tutorial, we learned how to replace a substring with a new value in this string in JavaScript, using replace() method, with examples.