Get the Index of a Character in a String in JavaScript

avatar

Borislav Hadzhiev

Sat Oct 09 20212 min read

banner

Photo by Hannah Busing

Get the Index of a Character in a String #

To get the index of a character in a string, you use the indexOf() method, passing it the specific character as a parameter. This method returns the index of the first occurrence of the character or -1 if the character is not found.

index.js
const str = 'hello world'; const index = str.indexOf('l'); console.log(index); // ๐Ÿ‘‰๏ธ 2

In the example, we use the String.indexOf method to get the index of the first occurrence of the l character in the string hello world.

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

If the indexOf method does not find the specified character in the string, it returns -1.

Get the Index of a Character's Last Occurrence in a String #

To get the index of a character's last occurrence in a string, you use the lastIndexOf() method, passing it the specific character as a parameter. This method returns the index of the last occurrence of the character or -1 if the character is not found.

index.js
const str = 'hello world'; const lastIndex = str.lastIndexOf('l'); console.log(lastIndex); // ๐Ÿ‘‰๏ธ 9

In the code snippet, we use the String.lastIndexOf method to get the index of the last occurrence of the l character in the string hello world.

The last l is the 10th character in the string, therefore it's at index 9.

The lastIndexOf method returns -1 if the character is not found in the string.

Get the Index of all Occurrences of a Character in a String #

To get the index of all of a character's occurrences in a string:

  1. Create an array that will store the indexes.
  2. In a for loop, loop for string.length iterations, checking if the character at the current index is equal to the specific character.
  3. If the equality check passes, push the character's index to the array.
index.js
const str = 'hello world'; const indexes = []; for (let i = 0; i < str.length; i++) { if (str[i] === 'l') { indexes.push(i); } } console.log(indexes); // ๐Ÿ‘‰๏ธ [2, 3, 9]

We used a for loop, because it allows us to keep track of the current index in a simple way.

For each iteration, we check if the character at the current index is equal to the character we're trying to get the indexes of.

If the condition is met, we push the current index to the indexes array.

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