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 replace() method to replace all the match elements otherwise the method replace 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 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.

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

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.