How to use substr() method In Javascript
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.
// Function to remove text
function removeText() {
// Input string
let originalText = 'w3wiki';
// Using substr with index range to remove text
let newText = originalText.substr(3, 9);
// Display text
console.log(newText);
}
// Function call
removeText();
Output
ksForGeek
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