How to use replaceAll() method In Javascript

  • Declare a constant str variable with the initial string “GeeksforGEEKS”.
  • Now, use the String.replaceAll() method to replace all occurrences of “GEEKS” in the str with “Geeks”, assigning the result to finalResult and logging it to the console.

Example: The below code is practical implementation of the above-discussed approach.

Javascript




const str = "GeeksforGEEKS";
const finalResult =
    str.replaceAll("GEEKS", "Geeks");
console.log("Before replacement: ", str)
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....