JavaScript Code


How to replace all occurrences of a string in JavaScript?


Replace all occurrences of a string in JavaScript

In this tutorial, you are given a string and substring. Replace all occurrences of the substring in string, using JavaScript.

Solution

To replace all occurrences of a string using JavaScript, use String replace() method. Call replace() method on the string, pass the search string as regular expression with global search, and the replacement string, as arguments. With this setup, replace() method returns a new string with all the occurrences of the search string replaced with replacement string.

myStr.replace(/searchString/g, replacementString)

Program

1. Given a string value is str. Replace "apple" at all occurrences with "mango" in str.

str = "apple banana apple cherry guava";
output = str.replace(/apple/g, "mango");
console.log(output);