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

Updated on: 20-Aug-2020

620 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements