Replace all occurrences of a string in JavaScript ?

You might want to replace all the occurrences of the matched substrings with the new string in JavaScript.

You can use the combination of regular expression with the replace method defined in the String type to do it.

How to replace all the occurrences of a string in JavaScript ?

var inputStr = "Senthil is a Windows Phone Developer and Windows Phone enthusiast";
var regularexpress = new RegExp('/Windows Phone', "g");
var newStr = inputStr.replace(regularexpress, "Mobile");
console.log(newStr); 

image

In the above code snippet , we created a new RegExp object specifying the text “Windows Phone” to be replace as the first parameter (You could define the pattern here). The second parameter (“g”) is the global flag indicating that all the occurrences should be replaced.

Leave a Reply