
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
Keeping only redundant words in a string in JavaScript
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
- Related Articles
- Keeping only alphanumerals in a JavaScript string in JavaScript
- Counting the number of redundant characters in a string - JavaScript
- Reversing words in a string in JavaScript
- Finding duplicate "words" in a string - JavaScript
- Reversing words present in a string in JavaScript
- Swapping adjacent words of a String in JavaScript
- Arranging words in Ascending order in a string - JavaScript
- Add two array keeping duplicates only once - JavaScript
- Reversing the words within keeping their order the same JavaScript
- Interchanging first letters of words in a string in JavaScript
- Finding the number of words in a string JavaScript
- Replace words of a string - JavaScript
- Reversing words within a string JavaScript
- Reversing consonants only from a string in JavaScript
- Reversing the even length words of a string in JavaScript

Advertisements