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:
- First parameter is passed as a string pattern to be searched in the provided string
- 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.