HomeJavaScriptReplace all occurrences of a string in JavaScript ?

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

You May Also Like

You might want to filter an array in JavaScript by passing the filter criteria and return the filtered array. In...
You can flatten a 2-D array in JavaScript using the concat and apply method as shown in the below code...
Assume that you have an angle in degree and you wish to convert it to radians in JavaScript so that...