In the previous tutorial we learnt the syntax of Javascript replace string function and its simple example to replace the first occurrence of specified string pattern. That is the default functionality of the method. Here we will learn how to replace all the occurrences of specified string with a new string using replace function’s extended parameter ‘g’.
Javascript Replace String Example
var myString = new String(); myString = "This is second example"; document.write(myString.replace(/ /g,"-"));
Output
This-is-second-example‘g’ parameter works as a directive for the replace function that directs the javascript to search for all the occurrences of specified string pattern in the given string and place the new string pattern or character in its place. Next see examples of case insensitive javascript replace string function. By default this function works with case sensitive approach.
Continue to next tutorial: case insensitive javascript replace string function to learn case insensitive find and replace method.