Javascript string replace() method. In this tutorial, we will explain the javascript string.replace() method with the definition of this method, syntax, parameters, and several examples.
JavaScript String Replace()
Definition: – 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
string.replace(search_value, new_value);
Parameters of string replace method
| 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. |
Ex:-
var str = "My fav car color is black";
var res = str.replace(/blue/g, "silver");
document.write( "Output :- " + res );
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>javascript string replace() Method</title>
</head>
<body>
<script type = "text/javascript">
var str = "My fav car color is black";
var res = str.replace(/blue/g, "silver");
document.write( "Output :- " + res );
</script>
</body>
</html>
Result of the above code is:
Output :- My fav car color is silver
Ex-2
Here we will take the second 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 );
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>javascript string replace() Method</title>
</head>
<body>
<script type = "text/javascript">
var str = "My fav bike color is Black";
var res = str.replace(/black/gi, "white");
document.write( "Output :- " + res );
</script>
</body>
</html>
Result of the above code is:
Output :- My fav bike color is white
Ex-3
Here we will take a new 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 );
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>javascript replace all string</title>
</head>
<body>
<script type = "text/javascript">
var str = 'this is the sentence to end all sentences';
var res = str.replace(new RegExp('sentence', 'g'), 'message');
document.write( "Output :- " + res );
</script>
</body>
</html>
Result of the above code is:
Output :- this is the message to end all messages