Get all Indexes of a Character in a String in JavaScript


Borislav Hadzhiev

Fri Oct 08 20211 min read

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.
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 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.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee