JavaScript - Remove Text From a String
Here are the different approaches to remove specific text from a string in JavaScript, starting from the most commonly used approaches
Using replace() Method - Best Method
The replace() method is a direct and widely used method to remove specific text by replacing it with an empty string "". This method becomes more powerful with regular expressions for multiple or case-insensitive replacements.
let s1 = "Hello, welcome to JavaScript programming!";
let s2 = s1.replace("JavaScript", "");
console.log(s2);
Output
Hello, welcome to programming!
To remove all occurrences of text, use a regular expression with the g (global) flag
let s1 = "Hello, JavaScript JavaScript!";
let s2 = s1.replace(/JavaScript/g, "");
console.log(s2);
Output
Hello, !
Using slice() Method
The slice() method can remove a section of a string by specifying a range you want to keep. You’ll need to identify the position of the text to be removed with indexOf().
let s1 = "Hello, JavaScript world!";
let start = s1.indexOf("JavaScript");
let s2 = s1.slice(0, start) + s1.slice(start + "JavaScript".length);
console.log(s2);
Output
Hello, world!
Using split() and join()
Using split() on the specific text will divide the string at each occurrence, creating an array. You can then use join() to bring it back together without the text.
let s1 = "Hello, JavaScript world!";
let s2 = s1.split("JavaScript").join("");
console.log(s2);
Output
"Hello, world!"
Using substring() with indexOf()
Find the position of the text to be removed using indexOf(), then use substring() to extract the parts before and after that text.
let s1 = "Hello, JavaScript world!";
let start = s1.indexOf("JavaScript");
let s2 = s1.substring(0, start) + s1.substring(start + "JavaScript".length);
console.log(s2);
Output
Hello, world!
The replace() method is typically the most relevant due to its simplicity and versatility, especially for multi-instance or case-insensitive text removal.