Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Removing a specific substring from a string in JavaScript
We are given a main string and a substring, our job is to create a function, let's say removeString() that takes in these two arguments and returns a version of the main string which is free of the substring.
Here, we need to remove the separator from a string, for example:
this-is-a-string
Using split() and join() Method
The most common approach is to split the string by the substring and then join the parts back together:
const removeString = (string, separator) => {
// we split the string and make it free of separator
const separatedArray = string.split(separator);
// we join the separatedArray with empty string
const separatedString = separatedArray.join("");
return separatedString;
}
const str = removeString('this-is-a-string', '-');
console.log(str);
thisisastring
Using replace() Method
Another approach uses the replace() method with a regular expression to remove all occurrences:
const removeStringReplace = (string, substring) => {
// Create a global regex to replace all occurrences
const regex = new RegExp(substring, 'g');
return string.replace(regex, '');
}
const str2 = removeStringReplace('this-is-a-string', '-');
console.log(str2);
// Example with multiple occurrences
const str3 = removeStringReplace('hello--world--test', '--');
console.log(str3);
thisisastring helloworldtest
Using replaceAll() Method
For modern JavaScript environments, replaceAll() provides the simplest solution:
const removeStringReplaceAll = (string, substring) => {
return string.replaceAll(substring, '');
}
const str4 = removeStringReplaceAll('this-is-a-string', '-');
console.log(str4);
// Works with longer substrings too
const str5 = removeStringReplaceAll('remove_this_remove_this_text', '_this_');
console.log(str5);
thisisastring removeremovetext
Comparison
| Method | Browser Support | Performance | Use Case |
|---|---|---|---|
split() + join() |
All browsers | Good | Simple substrings |
replace() + regex |
All browsers | Good | Complex patterns |
replaceAll() |
ES2021+ | Best | Modern environments |
Conclusion
Use replaceAll() for modern JavaScript environments, or split().join("") for broader browser compatibility. Both methods effectively remove all occurrences of a substring from a string.
