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.

Recent JavaScript Tutorials

Javascript FSO ShortPath property

Javascript FileSystemObject (FSO) provides a ShortPath property that can be accessed using the folder object or file object returned by the GetFolder or GetFile method.

Javascript FSO Path Property

Javascript FileSystemObject (FSO) provides the Path property that can be accessed through the file object or folder object returned by the GetFile or GelFolder method

Javascript FSO Type property

Javascript FileSystemObject (FSO) provides a Type property that can be accessed through file object or folder object returned by the GetFile or GetFolder method

Javascript FSO ShortName property

Javascript FileSystemObject (FSO) provides a ShortName property that can be accessed using the folder object or file object returned by the GetFolder or GetFile method.

Javascript FSO Name Property

Javascript FileSystemObject (FSO) provides a Name property that can be accessed using file object or folder object.