Replace String Function in Javascript is used to replace the specified characters with new characters in the provided string.

Syntax

stringObject.replace([string pattern to find], [new string]);

Replace function takes 2 parameters:

  1. First parameter is passed as a string pattern to be searched in the provided string
  2. Second parameter is passed as a string of new characters to be placed.

In the first parameter you can use flags also e.g.: to search the whole string for replacing the specified characters you can use “g” and for case insensitive searching you can use “i”.

Example of JavaScript Replace String Function

var myString = new String();

myString = "This is first example";

document.write(myString.replace(/ /,"-"));

Above example will replace the first occurrence of space with hyphen “-“.

Output

This-is first example

Without specifying any search criteria it will search for the first occurrence of specified character that is to be replaced and will return the string by replacing the pattern with specified string or character. As you can see above example has returned the string with replaced character from the left side. It shows that javascript starts string traversing from left to right. Next learn from other Javascript Replace String Function Examples, how to find and replace all the occurrences of specified pattern with new string pattern or characters.

Continue to next tutorial: Javascript Replace String Function Examples to learn how to replace all the occurrences of specified string pattern.

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.