在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 祝福语大全简短6个
11 祝球员赛前祝福语简短
12 师生聚餐的祝福语简短
13 异性朋友简短生日祝福语
14 圣诞饭店祝福语大全简短
15 祝福语大全简短赞美同学
16 亲戚生日红包祝福语简短
17 教练生日祝福语 简短独特
18 庆双节祝福语简短