從第二 JavaScript 字串中移除第一個字串的所有字元


假設我們有兩個字串,其中包含的字元沒有特定順序。我們需要編寫一個函式,該函式接收這兩個字串,並返回第二個字串的修改版本,其中省略了所有存在於第一個字串中的字元。

以下是我們的字串 −

const first = "hello world";
const second = "hey there";

以下是我們用於從第二個字串中移除所有第一個字串字元的函式 −

const removeAll = (first, second) => {
   const newArr = second.split("").filter(el => {
      return !first.includes(el);
   });
   return newArr.join("");
};

為此函式編寫程式碼 −

示例

const first = "hello world";
const second = "hey there";
const removeAll = (first, second) => {
   const newArr = second.split("").filter(el => {
      return !first.includes(el);
   });
   return newArr.join("");
};
console.log(removeAll(first, second));

輸出

控制檯中的輸出將為 −

yt

更新於: 31-8-2020

300 次瀏覽

開啟你的 職業

透過完成課程獲得認證

開始
廣告