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