If string includes words in array, remove them JavaScript

In JavaScript, you may need to remove specific words from a string based on an array of target words. This is useful for content filtering, text cleaning, or removing unwanted terms from user input.

Problem Overview

We need to create a function that removes all occurrences of words present in an array from a given string, while handling whitespace properly to avoid multiple consecutive spaces.

Method 1: Using reduce() with Regular Expressions

const string = "The weather in Delhi today is very similar to the weather in Mumbai";
const words = [
    'shimla', 'rain', 'weather', 'Mumbai', 'Pune', 'Delhi', 'tomorrow', 'today', 'yesterday'
];

const removeWords = (str, arr) => {
    return arr.reduce((acc, val) => {
        const regex = new RegExp(`\b${val}\b`, "gi");
        return acc.replace(regex, '');
    }, str).replace(/\s+/g, ' ').trim();
};

console.log(removeWords(string, words));
The in is very similar to the in

Method 2: Using split() and filter()

const removeWordsFilter = (str, wordsToRemove) => {
    return str.split(' ')
        .filter(word => !wordsToRemove.includes(word.toLowerCase()))
        .join(' ');
};

const testString = "The weather in Delhi today is very nice";
const wordsArray = ['weather', 'delhi', 'today'];

console.log(removeWordsFilter(testString, wordsArray));
The in is very nice

Method 3: Case-Insensitive with Word Boundaries

const removeWordsCaseInsensitive = (str, wordsToRemove) => {
    let result = str;
    wordsToRemove.forEach(word => {
        const regex = new RegExp(`\b${word}\b`, 'gi');
        result = result.replace(regex, '');
    });
    return result.replace(/\s+/g, ' ').trim();
};

const text = "JavaScript is great and JAVASCRIPT rocks";
const removeList = ['javascript', 'great'];

console.log(removeWordsCaseInsensitive(text, removeList));
is and rocks

Key Points

  • \b ensures word boundaries, preventing partial matches
  • gi flags make the search global and case-insensitive
  • /\s+/g replaces multiple spaces with single spaces
  • trim() removes leading and trailing whitespace

Comparison

Method Performance Case Sensitivity Word Boundaries
reduce() with RegExp Good Configurable Yes
split() and filter() Fast Manual handling Automatic
forEach with RegExp Good Case-insensitive Yes

Conclusion

The reduce() method with regular expressions provides the most flexible approach for removing words from strings. Use word boundaries (\b) to ensure accurate matching and proper whitespace handling for clean results.

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

846 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements