The JavaScript replace() method searches for the specified string that you want to replace and replaces it with your specified new string.
variable.replace("string to replace", "replacement string");
Here are five examples of the replace() method.
Example 1:
Basic example. Replace lamb
with cat
.
<html>
<head>
<title>Example 1</title>
</head>
<body>
<script>
var string = "Mary had a little lamb.";
var result = string.replace("lamb", "cat");
console.log(result);
// output: Mary had a little cat.
</script>
</body>
</html>
Example 2:
Using variables in the replace() method.
<html>
<head>
<title>Example 2</title>
</head>
<body>
<script>
var string = "Mary had a little lamb";
var find = "lamb";
var replacement = "dog";
var result = string.replace(find, replacement);
console.log(result);
// output: Mary had a little dog.
</script>
</body>
</html>
Example 3:
Using a regular expression (regex).
<html>
<head>
<title>Example 3</title>
</head>
<body>
<script>
var string = "Mary had a little lamb";
var result = string.replace(/lamb/i, "bird");
console.log(result);
// output: Mary had a little bird.
</script>
</body>
</html>
Example 4:
Declaring a replacer function before the replace() method.
<html>
<head>
<title>Example 4</title>
</head>
<body>
<script>
function myFunction(match, $1, $2) {
return $1 + ' big rabbit';
};
var string = "Mary had a little lamb, whose fleece was white as snow";
var result = string.replace(/(Mary had a) (little lamb)/i, myFunction);
console.log(result);
// output: Mary had a big rabbit, whose fleece was white as snow.
</script>
</body>
</html>
Example 5:
Using an anonymous replacement function.
<html>
<head>
<title>Example 5</title>
</head>
<body>
<script>
var string = "Mary had a little lamb, whose fleece was white as snow";
var result = string.replace(/(Mary had a) (little lamb)/i, function(match, $1, $2){
return $1 + ' big rabbit';
});
console.log(result);
// output: Mary had a big rabbit, whose fleece was white as snow.
</script>
</body>
</html>