We can use JavaScript to remove a substring from a string by using the JavaScript String replace() method.
text.replace("some_substring", "");
Let’s see an example of this below.
Let’s use the code above on a string and see the results.
var somestring = "After running the replace method this is the text we want to remove, this string should not have the substring we want to remove in it."
somestring = somestring.replace(" this is the text we want to remove", "");
console.log(somestring);
#Output
After running the replace method, this string should not have the substring we want to remove in it.
Note that this code will only remove the first instance of the substring. Let’s say we want to remove all cases of the substring from our string. We would simply have to use the JavaScript replaceAll() method.
var somestring = "After running spam the replace method, spam this string should not have spam any of the substrings spam we want to removed spam in it."
somestring = somestring.replaceAll("spam", "");
console.log(somestring);
#Output
After running the replace method, this string should not have any of the substrings we want to removed in it.
Finally, we can wrap our code in a function so that we can reuse it to remove any substring from a string. Our function will take the string and the substring you want to be removed as parameters, and return the new string without the substring in it.
function remove_substring_from_string(str,substr){
return str.replaceAll(substr, "");
};
var somestring = "After running spam the replace method, spam this string should not have spam any of the substrings spam we want removed spam in it."
console.log(remove_substring_from_string(somestring,"spam "));
#Output
After running the replace method, this string should not have any of the substrings we want removed in it.
Hopefully this article has been useful for you to understand how to use JavaScript to remove substring from string.