How to use indexOf() and slice() methods In Javascript
- 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.
Example: The below code will explain the use of the indexOf() and slice() methods to replace all occurences of a substring.
Javascript
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: 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