
- 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
Finding duplicate "words" in a string - 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 = "big black bug bit a big black dog on his big black nose";
Then the output should be −
const output = "big black";
Example
Let’s write the code for this function −
const str = "big black bug bit a big black dog on his big black nose"; const findDuplicateWords = 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(findDuplicateWords(str));
Output
The output in the console: −
big black
- Related Articles
- Finding the number of words in a string JavaScript
- Finding words in a matrix in JavaScript
- Finding top three most occurring words in a string of text in JavaScript
- Finding mistakes in a string - JavaScript
- Finding n most frequent words from a sentence in JavaScript
- Reversing words in a string in JavaScript
- Finding missing letter in a string - JavaScript
- Reversing words present in a string in JavaScript
- Replace words of a string - JavaScript
- Reversing words within a string JavaScript
- Finding shortest word in a string in JavaScript
- Finding hamming distance in a string in JavaScript
- Swapping adjacent words of a String in JavaScript
- Finding second smallest word in a string - JavaScript
- Finding number of spaces in a string JavaScript

Advertisements