
- 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 the index of first character that appears twice in a string in 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.
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
Following is the output on console −
2
- Related Articles
- Return index of first repeating character in a string - JavaScript
- Finding the index of the first repeating character in a string in JavaScript
- Find the character in first string that is present at minimum index in second string in Python
- Find the index of the first unique character in a given string using C++
- Finding the first non-repeating character of a string in JavaScript
- Finding two missing numbers that appears only once and twice respectively in JavaScript
- Program to find the index of first Recurring Character in the given string in Python
- Return the element that appears for second most number of times in the array JavaScript
- Find the element that appears once in an array where every other element appears twice in C++
- How to return the index of first unique character without inbuilt functions using C#?
- Search index of a character in a string in Java
- Number of times a string appears in another JavaScript
- Find last index of a character in a string in C++
- Finding the index of the first element that violates the series (first non-consecutive number) in JavaScript
- First Unique Character in a String in Python

Advertisements