
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Index of First Repeating Character in a String in JavaScript
We are required to write a JavaScript function that takes in a string and returns the index of the first character that appears twice in the string. If there is no such character then we should return -1.
Let’s say the following is our string −
const str = 'Hello world, how are you';
We need to find the index of the first repeating character.
Example
The code for this will be −
const str = 'Hello world, how are you'; const firstRepeating = str => { const map = new Map(); for(let i = 0; i < str.length; i++){ if(map.has(str[i])){ return map.get(str[i]); }; map.set(str[i], i); }; return -1; }; console.log(firstRepeating(str));
Output
The output in the console will be −
2
Advertisements