How to use the replace() method with regular expression In Javascript

  • First, declare a string variable str with the value “GeeksforGEEKS”.
  • Now, declare a substring variable with the value “GEEKS” to search for and replace.
  • Use the replace method with a regular expression to globally replace all instances of the substring with the replacement value “geeks”.
  • It logs the result which will be “Geeks For geeks “.

Example: The below code will explain the use of replace() method with regular expression.

Javascript




let str = "GeeksforGEEKS";
let substring = "GEEKS";
let replacement = "Geeks";
console.log("Before replacement: ", str)
let finalResult =
    str.replace(new RegExp(substring, "g"),
        replacement);
 
console.log("After Replacement: ", finalResult);


Output

Before replacement:  GeeksforGEEKS
After Replacement:  w3wiki

Replace all Occurrences of a Substring in a String in JavaScript

In Javascript, a string is a sequence of characters represented with quotation marks. We are given a string and we need to replace all occurrences of a substring from the given string.

Table of Content

  • Using replace() method with regular expression
  • Using indexOf() and slice() methods
  • Using replaceAll() method

Similar Reads

Using the replace() method with regular expression

First, declare a string variable str with the value “GeeksforGEEKS”. Now, declare a substring variable with the value “GEEKS” to search for and replace. Use the replace method with a regular expression to globally replace all instances of the substring with the replacement value “geeks”. It logs the result which will be “Geeks For geeks “....

Using indexOf() and slice() methods

...

Using replaceAll() method

The indexOf() method finds the index of the first occurrence of the substring. If the index is greater than or equal to 0 (found a match), it slices the string before and after the match and inserts the replacement. It recursively calls itself to keep replacing all other matches. It returns the final string after replacing all matches....