如果字符串中包含单词,请删除它们。
给我们一个字符串和一个字符串数组;我们的工作是编写一个函数,从字符串中删除数组中存在的所有子字符串。
这些子字符串是完整的单词,因此我们也应该删除开头或结尾的空格,以免两个空格一起出现。
因此,让我们为该函数编写代码-
示例
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