
- 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
Return index of first repeating character in a string - JavaScript
We are required to write a JavaScript function that takes in a string and returns the index of first character that appears twice in the string.
If there is no such character then we should return -1. Following is our string −
const str = 'Hello world, how are you';
Example
Following is the code −
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
Following is the output in the console −
2
- Related Articles
- Finding the index of the first repeating character in a string in JavaScript
- Return the index of first character that appears twice in a string in JavaScript
- Finding the first non-repeating character of a string in JavaScript
- Finding first non-repeating character JavaScript
- Find first repeating character using JavaScript
- Repeating each character number of times their one based index in a string using JavaScript
- First non-repeating character using one traversal of string in C++
- How to find its first non-repeating character in a given string in android?
- Detecting the first non-repeating string in Array in JavaScript
- Find the index of the first unique character in a given string using C++
- Maximum consecutive repeating character in string in C++
- How to build a string with no repeating character n separate list of characters? in JavaScript
- Find the first non-repeating character from a stream of characters in Python
- How to return the index of first unique character without inbuilt functions using C#?
- Search index of a character in a string in Java

Advertisements