只保留 JavaScript 中字串中的重複單詞


我們需要編寫一個 JavaScript 函式,該函式接受一個字串並返回一個包含原始字串中出現多次的單詞的新字串。

例如

如果輸入字串為 -

const str = 'this is a is this string that contains that some repeating words';

輸出

那麼輸出應為 -

const output = 'this is that';

讓我們針對此函式編寫程式碼 -

示例

程式碼如下 -

const str = 'this is a is this string that contains that some repeating
words';
const keepDuplicateWords = str => {
   const strArr = str.split(" ");
   const res = [];
   for(let i = 0; i < strArr.length; i++){
      if(strArr.indexOf(strArr[i]) !== strArr.lastIndexOf(strArr[i])){
         if(!res.includes(strArr[i])){
            res.push(strArr[i]);
         };
      };
   };
   return res.join(" ");
};
console.log(keepDuplicateWords(str));

輸出

控制檯中的輸出 -

this is that

最近更新日期:2020 年 10 月 17 日

352 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.