문자열을 받아서 원래 문자열에 두 번 이상 나타난 단어만 포함하는 새 문자열을 반환하는 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