Skip to content

JavaScript replace() method | Examples

  • by

JavaScript replaces() method is used to replace the matched substring with a new substring. This returns a new string with the specified string/regex replaced.

string.replace(searchValue, newValue)

This method searches a string for a value or a regular expression.

JavaScript replace() method

Simple example code replaces the first occurrence.

<!DOCTYPE html>
<html lang="en">
<body>
  <script>

    const text = "Java is awesome. Java is fun."
    let pattern = "Java";
    // replace the first Java with JavaScript
    let new_text = text.replace(pattern, "JavaScript");
    console.log(new_text);

    const message = "ball bat";
    // replace the first b with T
    let result = message.replace('b', 'T');

console.log(result);

  </script>
</body>
</html>

Output:

JavaScript replace method

Replace all occurrences

We can use a global search modifier with the replace() method to replace all the match elements otherwise the method replaces only the first match.

You need to use a regex with a g switch (global search). For example, /Java/g instead of /Java/.

const text = "Java is awesome. Java is fun."

const res = text.replace(/Java/g, "JavaScript");
console.log(res);

Output: JavaScript is awesome. JavaScript is fun.

Case-Insensitive Replacement

JavaScript also provides an ignore flag to make the method case-insensitive.

let text = "Mr Blue has a blue house and a blue car";
let result = text.replace(/blue/gi, "red");
console.log(result)

Output: Mr red has a red house and a red car.

Example with Replacement Function

A replacement function can provide more control over the replacement process, such as using matched substrings or performing additional logic.

Using a Replacement Function

let originalString = "The quick brown fox jumps over the lazy dog.";
let newString = originalString.replace(/(\w+)\s(\w+)/g, function(match, p1, p2) {
    return p2 + " " + p1;
});
console.log(newString); // Output: "quick The fox brown over jumps lazy the dog."

In this example, the replacement function swaps each pair of words. The function parameters are:

  • match: The entire matched substring.
  • p1, p2, etc.: The captured groups (submatches) defined by parentheses in the regex.

Do comment if you have any doubts or suggestions on this JS string method topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading