在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
热门推荐
10 经典新婚祝福语英文简短
11 乔迁祝福语简短笑话作文
12 有趣虎年新春祝福语简短
13 妹妹结婚伴娘祝福语简短
14 家长不续费祝福语简短
15 基金赚钱祝福语简短英文
16 韩语妹妹生日祝福语简短
17 韩语学生毕业祝福语简短
18 公司新年祝福语简短的