Skip to content

JavaScript string replace RegEx

  • by

In JavaScript, you can use the replace() method along with regular expressions (RegEx) to replace substrings within a string. The replace() method allows you to replace matches of a pattern with a new value.

Here’s the basic syntax for using the replace() method with a regular expression in JavaScript:

string.replace(regexp, newSubstr)
  • string is the original string that you want to modify.
  • regexp is a regular expression pattern to match within the string.
  • newSubstr is the replacement substring that will be used to replace the matches.

Here are a few examples to illustrate how you can use replace() with regular expressions:

1. Replacing a specific substring with a new value:

const originalString = "Hello, World!";
const newString = originalString.replace("World", "JavaScript");
console.log(newString); // Output: "Hello, JavaScript!"

2. Replacing all occurrences of a specific substring using a regular expression with the /g flag:

const originalString = "Hello, World! Hello, World!";
const newString = originalString.replace(/World/g, "JavaScript");
console.log(newString); // Output: "Hello, JavaScript! Hello, JavaScript!"

3. Replacing case-insensitive occurrences of a substring using the /i flag:

const originalString = "Hello, World!";
const newString = originalString.replace(/world/i, "JavaScript");
console.log(newString); // Output: "Hello, JavaScript!"

4. Using capturing groups in the regular expression and referencing them in the replacement:

const originalString = "John Doe";
const newString = originalString.replace(/(\w+)\s(\w+)/, "$2, $1");
console.log(newString); // Output: "Doe, John"

(\w+) captures the first and last name as separate groups, and $1 and $2 are placeholders that reference those groups in the replacement string.

JavaScript string replace RegEx example

Simple example code that demonstrates how to use the replace() method with regular expressions in JavaScript:

const sentence = "The quick brown fox jumps over the lazy dog.";

// Replace all occurrences of the word "the" (case-insensitive) with "a"
const newSentence = sentence.replace(/the/gi, "a");

console.log(newSentence);

Output:

JavaScript string replace RegEx

Feel free to modify the regular expression and replacement string to suit your specific needs when using the replace() method with regular expressions in JavaScript.

Comment if you have any doubts or suggestions on this Js RegEx 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