Javascript string replace() method; Through this tutorial, i am going to show you javascript string.replace() method with the help of it’s syntax, parameters, and examples.
JavaScript String Replace()
- What is String Replace()
- Syntax of JavaScript String Replace()
- Parameters of JavaScript String Replace()
- Example 1 – JavaScript String Replace()
- Example 2 – JavaScript String Replace()
- Example 3 – JavaScript String Replace()
What is String Replace()
The JavaScript string replace() method searches a string for a specified value or a regular expression, or keyword, and replace match search string to given string, returns a new string
Syntax of JavaScript String Replace()
See the following syntax of string replace() method; as shown below:
string.replace(search_value, new_value);
Parameters of JavaScript String Replace()
See the parameters of string replace() method; as shown below:
Parameter | Description |
---|---|
search_value | This is the first parameter and required. The value, or regular expression, that will be replaced by the given value |
new_value | This is the second parameter and required. The given value to replace the search value. |
Example 1 – JavaScript String Replace()
Here, i will take first example using string replace() method; as shown below:
var str = "My fav car color is black"; var res = str.replace(/black/g, "silver"); document.write( "Output :- " + res );
Output of the above code is:
Output :- My fav car color is silver
Example 2 – JavaScript String Replace()
Take next example of string replace() method with case-insensitive string:
var str = "My fav bike color is Black"; var res = str.replace(/black/gi, "white"); document.write( "Output :- " + res );
Output of the above code is:
Output :- My fav bike color is white
Example 3 – JavaScript String Replace()
Take third example of javascript string replace all with regexp:
var str = 'this is the sentence to end all sentences'; var res = str.replace(new RegExp('sentence', 'g'), 'message'); document.write( "Output :- " + res );
Output of the above code is:
Output :- this is the message to end all messages