只保留 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
廣告
資料結構
網路
關係型資料庫管理系統(RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言
C++
C#
MongoDB
MySQL
Javascript
PHP