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">

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

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




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");

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");

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. Required fields are marked *