How to use replace() method with Regex In Javascript
This method is used to remove all occurrences of the string specified, unlike the previous method. A regular expression is used instead of the string along with the global property. This will select every occurrence in the string and it can be removed by using an empty string in the second parameter.
Syntax:
string.replace(/regExp/g, '');
Example: This example uses the above approach to replace text from a string in JavaScript.
function removeText() {
// Input string
let originalText = 'w3wiki';
// Replace method with regEx
let newText = originalText.replace(/Geeks/g, '');
// Display output
console.log(newText);
}
// Function call
removeText();
Output
For
How to remove text from a string in JavaScript ?
We will have a string and we need to remove the given text from that string using JavaScript. We need to print the new string in the console.
These are the following methods to Remove Text from a String:
Table of Content
- Method 1: Using replace() method
- Method 2: Using replace() method with Regex
- Method 3: Using substr() method
- Method 4: Using replaceAll() method
- Method 5: Using split() and join() method