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

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

You May Also Like

JavaScript supports different types of operators that includes Assignment Operator JavaScript supports different types if Assignment Operators like = +=...
Assume that you have an angle in degree and you wish to convert it to radians in JavaScript so that...
The JavaScript elements and statements are placed within the script tag within the HTML page. You can specify the language...