在 JavaScript 中仅保留字符串中的冗余单词
javascriptweb developmentfront end technologyobject oriented programming更新于 2026/1/29 10:20:17
我们需要编写一个 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
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

