JavaScript Code

How to replace all occurrences of a string in JavaScript?

Problem Statement

given a string and substring, replace all occurrences of the substring in string, using JavaScript


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)


1. given string is str. replace "apple" at all occurrences with "mango" in str

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