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

javascriptweb developmentobject oriented programming更新于 2025/9/29 20:28:17

我们得到一个字符串和一个字符串数组;我们的工作是编写一个函数,从字符串中删除数组中存在的所有子字符串。

这些子字符串是完整的单词,因此我们还应该删除前导或尾随空格,以便没有两个空格一起出现。

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

示例

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 output for this code will be −

The in is very similar to the in

相关文章


有用资源