- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- 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
Advertisements
To Continue Learning Please Login
Login with Google