如果字串包含陣列中的單詞,則用 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.