Javascript Replace String Function

Updated on 20 Mar 2012,
Published on 11 Mar 2008

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


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".

JavaScript String Object Examples:

You can see the live samples and examples of JavaScript String Object from the following links:

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 "-".


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.


You can see the output of above discussed code from the following links:

Replace String Function 01

Replace String Function 02

Replace String Function 03

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

1 Responses to "Javascript Replace String Function"
Snehal Chauhan
Its easy but very good solution to use variable in from replace. I was searching for it.. Thanks for your help.

Leave a Comment
* required
* required
* will not be published
* optional
* hint:
  • Subscribe via Email