Replace all Occurrences of a Substring in a String in JavaScript
Given a String, the task is to replace all occurrences of a substring using JavaScript. The basic method to replace all substring of a string is by using string.replaceAll() method.
The string.replaceAll() method is used to search and replace all the matching substrings with a new string. We can use the regular expression as a pattern to find all the matching substrings.
Syntax
string.replaceAll(sunstring, replacement);
let str = "GEEKSforGEEKS";
let substring = "GEEKS";
let replacement = "Geeks";
// Replace all occurrences of substring
let updatedStr = str.replaceAll(substring, replacement);
// Updated string
console.log("Updated String:", updatedStr);
Output
Updated String: GeeksforGeeks
Table of Content
Using String replace() Method with Regular Expression
The string replace() method is used to search and replace a substings with a new string. We can use the regular expression as a pattern to find all the matching substrings.
Syntax
string.replace(substring, replacement);
let str = "GEEKSforGEEKS";
let substring = "GEEKS";
let replacement = "Geeks";
let updatedStr = str.replace(new RegExp(substring, "g"), replacement);
// Updated string
console.log("Updated String:", updatedStr);
Output
Updated String: GeeksforGeeks
Using indexOf() and slice() Methods
The indexOf() method finds the index of the first occurrence of the substring. Next, we can break the string from that index using str.slice() and insert the replacement string to get the required output.
str.indexOf(searchValue, startIndex);
string.slice(startingIndex, endingIndex);
let str = "GEEKSforGEEKS";
let substring = "GEEKS";
let replacement = "Geeks";
while (str.indexOf(substring) !== -1) {
let index = str.indexOf(substring);
str = str.slice(0, index) + replacement + str.slice(index + substring.length);
}
// Updated string
console.log("Updated String:", str);
Output
Updated String: GeeksforGeeks