在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
热门推荐
1 狗狗技能训练
5 如何训练狗狗笑
6 狗狗训练排便
9 狗狗响片训练
10 如何训练狗狗不捡食
11 狗狗尿训练
12 怎么训练狗狗找东西
13 狗狗训练站立
14 狗狗训练飞盘
15 鞍山狗狗训练
16 怎样训练泰迪狗狗谢谢
17 狗狗外出训练
18 怎么训练金毛狗狗大小便