檢查兩個字串並返回 JavaScript 中的通用單詞的函式


我們需要編寫一個 JavaScript 函式,該函式接受兩個字串作為引數。然後,該函式應檢查兩個字串是否存在公共字元,並準備一個包含這些字元的新字串。

最後,該函式應返回該字串。

此函式的程式碼如下:

示例

const str1 = "IloveLinux";
const str2 = "weloveNodejs";
const findCommon = (str1 = '', str2 = '') => {
   const common = Object.create(null);
   let i, j, part;
   for (i = 0; i < str1.length - 1; i++) {
      for (j = i + 1; j <= str1.length; j++) {
         part = str1.slice(i, j);
         if (str2.indexOf(part) !== −1) {
            common[part] = true;
         }
      }
   }
   const commonEl = Object.keys(common);
   return commonEl;
};
console.log(findCommon(str1, str2));

輸出

控制檯中的輸出為:

[
   'l', 'lo', 'lov',
   'love', 'o', 'ov',
   'ove', 'v', 've',
   'e'
]

更新於: 20-11-2020

683 次瀏覽

開啟你的 職業 生涯

透過完成課程獲得證書

開始
廣告
© . All rights reserved.