We are required to write a JavaScript function that takes in a string and returns a new string with only the words that appeared for more than once in the original string.
For example:
If the input string is −
const str = 'this is a is this string that contains that some repeating words';
Output
Then the output should be −
const output = 'this is that';
Let’s write the code for this function −
Example
The code for this will be −
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));
Output
The output in the console −
this is that