In this article, we will remove text from a string in JavaScript. There are three methods to remove the text from a string which are listed below:
Methods to Remove Text from a String
The replace() method is used to replace the specified string with another string. It takes two parameters, the first is the string to be replaced and the second is the string that is replaced from the first string. The second string can be given an empty string so that the text to be replaced is removed. This method however only removes the first occurrence of the string.
Syntax:
string.replace('textToReplace', '');
Example: This example replaces the first occurrence of the string.
Javascript
function removeText() {
let originalText = 'GeeksForGeeks' ;
let newText = originalText.replace( 'Geeks' , '' );
console.log(newText);
}
removeText();
|
Method 2: Using replace() method with Regex
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.
Javascript
function removeText() {
let originalText = 'GeeksForGeeks' ;
let newText = originalText.replace(/Geeks/g, '' );
console.log(newText);
}
removeText();
|
Method 3: Using substr() method
The substr() method is used to extract parts of a string between the given parameters. This method takes two parameters, one is the starting index and the other is the length of the string to be selected from that index. By specifying the required length of the string needed, the other portion can be discarded. This can be used to remove prefixes or suffixes in a string.
Syntax:
string.substr(start, length);
Example: This example uses the above approach to replace text from a string in JavaScript.
Javascript
function removeText() {
let originalText = 'GeeksForGeeks' ;
let newText = originalText.substr(3, 9);
console.log(newText);
}
removeText();
|
Example: In this article, we will use the JavaScript replaceAll() methods to remove all the occurrences of given text from the input string.
Javascript
function removeText() {
let originalText = 'GeeksForGeeks' ;
let newText = originalText.replaceAll( 'Geeks' , '' );
console.log(newText);
}
removeText();
|
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!