How to use the replace() method with regular expression In Javascript
- 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 “.
Example: The below code will explain the use of replace() method with regular expression.
Javascript
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: 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