javascript
  1. javascript-replace

JavaScript replace()

The replace() method is a built-in JavaScript function used to search for a specified string or a regular expression pattern and replace the matched occurrences with a new string. The original string remains unchanged, and a new string is returned by the method.

Syntax

string.replace(searchValue, replaceValue)
string.replace(regexp, replaceValue)
  • string: Required. The original string where the replacement should take place.
  • searchValue: Required. A string to be searched and replaced.
  • regexp: Required. A regular expression pattern to be searched and replaced.
  • replaceValue: Required. A string to replace the found searchValue or regexp.

Example

let str = "The quick brown fox jumps over the lazy dog.";
let newStr = str.replace('fox', 'cat');
console.log(newStr); // The quick brown cat jumps over the lazy dog.

let regex = /quick|lazy/gi;
newStr = str.replace(regex, 'slow');
console.log(newStr); // The slow brown fox jumps over the slow dog.

Output

The quick brown cat jumps over the lazy dog.
The slow brown fox jumps over the slow dog.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>String Replacement Example</title>
</head>
<body>

<!-- Display area for the output -->
<div id="output"></div>

<script>
    // Your JavaScript code
    let str = "The quick brown fox jumps over the lazy dog.";

    // Using replace() method with strings
    let newStr1 = str.replace('fox', 'cat');

    // Using replace() method with regular expression
    let regex = /quick|lazy/gi;
    let newStr2 = str.replace(regex, 'slow');

    // Display the output in the HTML document
    document.getElementById('output').innerHTML = `
        <p>Original String: "${str}"</p>
        <p>After replacing 'fox' with 'cat': "${newStr1}"</p>
        <p>After replacing 'quick' and 'lazy' with 'slow': "${newStr2}"</p>
    `;
</script>

</body>
</html>
Try Playground

Explanation

In the first example, replace() method searches for the string "fox" in the str variable and replaces it with "cat". The resulting string is then stored in the newStr variable.

In the second example, replace() method searches for the regular expression pattern /quick|lazy/gi in the str variable, which matches both "quick" and "lazy". Both these matched patterns are replaced with the string "slow". The resulting new string is stored in the newStr variable.

Use

The replace() method can be used in various scenarios, such as:

  • Replacing specific characters or strings in a string.
  • Normalizing strings by replacing special characters with their ASCII equivalents.
  • Parsing strings and manipulating them before displaying the final output.
  • Validating and sanitizing user input by replacing unwanted characters or patterns.

Important Points

  • The replace() method only replaces the first occurrence of the search string or regular expression pattern. To replace all the occurrences, we need to use a regular expression with the g flag.
  • The replace() method does not modify the original string. Instead, it returns a new string after the replacement operation.
  • If the search value is not found in the original string, the method returns the original string.
  • By default, the replace() method is case-sensitive. To ignore the case, we can use the i flag with a regular expression pattern.

Summary

The replace() method is a useful built-in function in JavaScript for string manipulation. We can replace a specific substring or use a regular expression pattern to replace more complex patterns. By using this method, we can sanitize user inputs, normalize strings, and manipulate data before final output.

Published on: