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
Remove all characters of first string from second JavaScript
When working with strings in JavaScript, you may need to remove all characters from one string that appear in another string. This is useful for filtering, data cleaning, or text processing tasks.
Let's say we have two strings with characters in no specific order. We need to write a function that takes these two strings and returns a modified version of the second string with all characters from the first string removed.
Example Strings
const first = "hello world"; const second = "hey there";
Using Array Methods (Recommended)
The most straightforward approach uses split(), filter(), and join() methods:
const first = "hello world";
const second = "hey there";
const removeAll = (first, second) => {
const newArr = second.split("").filter(el => {
return !first.includes(el);
});
return newArr.join("");
};
console.log(removeAll(first, second));
console.log(`Original: "${second}"`);
console.log(`Filtered: "${removeAll(first, second)}"`);
yt Original: "hey there" Filtered: "yt"
How It Works
The function works in three steps:
-
split("")converts the second string into an array of characters -
filter()keeps only characters that are NOT found in the first string -
join("")combines the filtered characters back into a string
Using Set for Better Performance
For longer strings, using a Set improves performance by making character lookups faster:
const removeAllOptimized = (first, second) => {
const charsToRemove = new Set(first);
return second.split("").filter(char => !charsToRemove.has(char)).join("");
};
const first = "hello world";
const second = "hey there everyone";
console.log(removeAllOptimized(first, second));
yt yn
Case-Sensitive vs Case-Insensitive
The default behavior is case-sensitive. For case-insensitive removal:
const removeAllCaseInsensitive = (first, second) => {
const charsToRemove = new Set(first.toLowerCase());
return second.split("").filter(char =>
!charsToRemove.has(char.toLowerCase())
).join("");
};
const first = "Hello World";
const second = "Hey There";
console.log("Case-sensitive:", removeAll(first, second));
console.log("Case-insensitive:", removeAllCaseInsensitive(first, second));
Case-sensitive: ey Tere Case-insensitive: yT
Comparison
| Method | Performance | Case Handling | Best For |
|---|---|---|---|
| Array.includes() | Good for short strings | Case-sensitive | Simple use cases |
| Set.has() | Better for long strings | Configurable | Performance-critical apps |
Conclusion
Use the array method approach for simple string filtering. For better performance with longer strings, convert the first string to a Set for O(1) character lookups instead of O(n) array searches.
