
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
If string includes words in array, remove them JavaScript
We are given a string and an array of strings; our job is to write a function that removes all the substrings that are present in the array from the string.
These substrings are complete words so we are also supposed to remove leading or trailing whitespace so that no two whitespaces appear together.
Therefore, let’s write the code for this function −
Example
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(` ${val}`, "g"); return acc.replace(regex, ''); }, str); }; console.log(removeWords(string, words));
Output
The output for this code will be −
The in is very similar to the in
- Related Articles
- Remove elements from array in JavaScript using includes() and splice()?
- How do I check if an array includes an object in JavaScript?
- Filter array with filter() and includes() in JavaScript
- Validating string with reference to array of words using JavaScript
- Python program to remove K length words in String
- Sorting words by last character present in them in JavaScript
- Reversing words in a string in JavaScript
- Finding duplicate "words" in a string - JavaScript
- Replace words of a string - JavaScript
- Reversing words within a string JavaScript
- Reversing words present in a string in JavaScript
- Order an array of words based on another array of words JavaScript
- Remove extra spaces in string JavaScript?
- Swapping adjacent words of a String in JavaScript
- If the element repeats, remove all its instances from array in JavaScript

Advertisements