Remove characters from a string contained in another string with JavaScript?

When working with strings in JavaScript, you might need to remove all characters from one string that appear in another string. This can be achieved using the replace() method combined with reduce().

Problem Statement

Given two strings, we want to remove all characters from the first string that exist in the second string:

var originalName = "JOHNDOE";
var removalName = "JOHN";
// Expected result: "DOE"

Solution Using replace() and reduce()

The reduce() method iterates through each character in the removal string, and replace() removes the first occurrence of that character from the original string.

const removeCharactersFromAString = (removalName, originalName) => 
    removalName.split('').reduce((obj, v) => obj.replace(v, ''), originalName);

var originalName = "JOHNDOE";
var removalName = "JOHN";

console.log("Original string:", originalName);
console.log("Characters to remove:", removalName);
console.log("Result:", removeCharactersFromAString(removalName, originalName));
Original string: JOHNDOE
Characters to remove: JOHN
Result: DOE

How It Works

The function works by:

  1. split('') - Converts the removal string into an array of characters
  2. reduce() - Iterates through each character
  3. replace(v, '') - Removes the first occurrence of each character from the original string

Alternative Approach Using Regular Expression

For removing all occurrences of each character (not just the first), you can use a regular expression:

const removeAllOccurrences = (removalName, originalName) => {
    const pattern = '[' + removalName.replace(/[.*+?^${}()|[\]\]/g, '\$&') + ']';
    return originalName.replace(new RegExp(pattern, 'g'), '');
};

var originalName = "JOHNJOHNDOE";
var removalName = "JOHN";

console.log("Original:", originalName);
console.log("Result:", removeAllOccurrences(removalName, originalName));
Original: JOHNJOHNDOE
Result: DOE

Comparison

Method Removes Performance
reduce() + replace() First occurrence only Good for small strings
Regular Expression All occurrences Better for complex patterns

Conclusion

Use reduce() with replace() for simple character removal. For removing all occurrences or complex patterns, regular expressions provide more control and better performance.

Updated on: 2026-03-15T23:18:59+05:30

425 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements