

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 Questions & Answers
- 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
- Sorting words by last character present in them in JavaScript
- Validating string with reference to array of words using JavaScript
- Reversing words in a string in JavaScript
- Replace words of a string - JavaScript
- Reversing words within a string JavaScript
- Order an array of words based on another array of words JavaScript
- Reversing words present in a string in JavaScript
- Swapping adjacent words of a String in JavaScript
- If the element repeats, remove all its instances from array in JavaScript
- Remove extra spaces in string JavaScript?
- JavaScript: How to check whether an array includes a particular value or not?
- Arranging words in Ascending order in a string - JavaScript
Advertisements