0

Finding the repeated characters

How to check if the character in a string is repeated using JavaScript

21st Aug 2019, 11:34 AM
Majd Alkwaja
Majd Alkwaja - avatar
1 Antwort
+ 1
If you want to remove repeated characters, you might just be able to use a set: console.log([...new Set(prompt("Enter string:", "kittens are cute").split(""))].join("")); First, you get input with prompt Then, turn it into an array with split("") Create a set (it removes duplicate values) Make the set into an array (with [...set] Make the array a string (with join("")) "kittens are cute" (string) ↓ 'k i t t e n s a r e c u t e' (array) ↓ 'k i t e n s a r c u' (set) ↓ 'k i t e n s a r c u' (array) ↓ "kitens arcu" (string) However, if you really just want the duplica4e values: // Using a set for duplicate values, so they are not duplicate let inp = prompt(), res = new Set(); for (const i of inp) // If first occurance isn't equal to last (at least twice) if (inp.indexOf(i) !== inp.lastIndexOf(i)) res.add(i); console.log(`Duplicate values: ${[...res].map(i => `'${i}'`).join(", ")}`);
21st Aug 2019, 11:42 AM
Airree
Airree - avatar