Get all Indexes of a Character in a String in JavaScript

avatar

Borislav Hadzhiev

Last updated: Oct 8, 2021

banner

Photo from Unsplash

Get all Indexes of a Character in a String #

To get all indexes of a specific character in a string:

  1. Create an empty array that will store the indexes.
  2. Use a for loop and loop from 0 up to the string's length.
  3. For each iteration of the loop, check if the character at that index is equal to the specific character. If it is, push the character's index to the indexes array.
index.js
const str = 'hello world'; const indexes = []; for (let index = 0; index < str.length; index++) { if (str[index] === 'l') { indexes.push(index); } } console.log(indexes); // 👉️ [2, 3, 9]

In the code snippet, we create an array that will store the indexes of the character l in the string hello world.

We use a simple for loop to iterate for str.length iterations and check whether each character is strictly equal to l.

If the condition is met, we push the index in the array.

Indexes are zero-based in JavaScript, therefore the first character in the string has an index of 0 and the last an index of str.length - 1.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.