在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