Open In App

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.

Using the replace() method with regular expression

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




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:  GeeksforGeeks

Using indexOf() and slice() methods

Example: The below code will explain the use of the indexOf() and slice() methods to replace all occurences of a substring.




function replaceAll(str, substring, replacement) {
    let index = str.indexOf(substring);
    if (index >= 0) {
        str =
            str.slice(0, index) + replacement +
            str.slice(index + substring.length);
        str = replaceAll(str, substring, replacement);
    }
    return str;
}
const str = "GeeksforGEEKS";
const subStr = "GEEKS";
const replacement = "Geeks";
console.log("Before replacement: ", str)
let finalResult =
    replaceAll(str, subStr, replacement);
console.log("After Replacement: ", finalResult);

Output
Before replacement:  GeeksforGEEKS
After Replacement:  GeeksforGeeks

Using replaceAll() method

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




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:  GeeksforGeeks

Article Tags :