Replace all occurrences of a string in JavaScript ?

Your 2020 Plan. Learn 20 minutes a day for 20 days. Online courses from €9.99.

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");


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

Your email address will not be published. Required fields are marked *