如果字符串包含数组中的单词,则用 JavaScript 删除它们


如果给了我们一个字符串和一个字符串数组,我们的任务是编写一个从字符串中删除所有存在于数组中的子字符串的函数。

这些子字符串是完整的单词,所以我们也要删除前导或尾随的空白,以使没有两个空白出现在一起。

因此,让我们编写这个函数的代码 −

示例

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));

输出

此代码的输出将是 −

The in is very similar to the in

更新于: 20-Aug-2020

692 次浏览

开启你的职业生涯

通过完成课程取得认证

立即开始
广告
© . All rights reserved.