Get Index of first, last or all occurrences in String in JS

avatar

Borislav Hadzhiev

3 min

banner

Photo from Unsplash

Table of Contents #

  1. Get the Index of a Character in a String in JavaScript
  2. Get the Index of a Character's Last Occurrence in a String
  3. Get the index of all occurrences of characters in a String

Get the Index of a Character in a String in JavaScript #

Use the String.indexOf() method to get the index of a character in a string, e.g. const index = str.indexOf('l');.

The String.indexOf() method returns the index of the first occurrence of the character or -1 if the character is not found in the string.

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

We used the String.indexOf method to get the index of the first occurrence of the l character in the string hello world.

JavaScript indexes are zero-based, so the first character has an index of 0 and the last character has an index of str.length - 1.

If the indexOf method doesn't find the specified character in the string, it returns -1.

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

Use the String.lastIndexOf() method to get the index of the last occurrence of a character in a string, e.g. const lastIndex = str.lastIndexOf('l');.

The String.lastIndexOf() method returns the index of the last occurrence of a character in a string or -1 if the character is not found.

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

We used 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, so it has an index of 9.

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

Get the index of all occurrences of characters in a String #

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

  1. Declare a new variable and initialize it to an empty array.
  2. Use a for loop to iterate over the string.
  3. Check if each character is equal to the specific character.
  4. Push the index of the matching characters into the new 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]

We declared a new variable and initialized it to an array.

The array will store the indexes of the character l in the string hello world.

We used a simple for loop to iterate for str.length iterations.

On each iteration, we check if each character is equal to l.

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]

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

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

Alternatively, you can use the String.split() method.

Get the index of all occurrences of characters in a String using split() #

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

  1. Use the String.split() method to split the string into an array of characters.
  2. Use the map() method to iterate over the array of characters.
  3. Check if each character is the specified character and return the corresponding index.
index.js
function findIndexes(string, char) { return string .split('') .map((c, idx) => { if (c === char) { return idx; } return -1; }) .filter(element => element !== -1); } const str = 'hello world'; const indexes = findIndexes(str, 'l'); console.log(indexes); // ๐Ÿ‘‰๏ธ [ 2, 3, 9 ]

We used the String.split() method to split the string into an array of characters.

index.js
const str = 'hello world'; // [ // 'h', 'e', 'l', 'l', // 'o', ' ', 'w', 'o', // 'r', 'l', 'd' // ] console.log(str.split(''));

The next step is to use the Array.map() method to iterate over the array of characters and check if each character is equal to the specified character.

index.js
const str = 'hello world'; const char = 'l'; // [ // -1, -1, 2, 3, -1, // -1, -1, -1, -1, 9, // -1 // ] console.log( str.split('').map((c, idx) => { if (c === char) { return idx; } return -1; }), );

If the current character is equal to the specified character, we return its index, otherwise, we return -1.

The last step is to use the Array.filter() method to filter out all -1 values from the array.

index.js
function findIndexes(string, char) { return string .split('') .map((c, idx) => { if (c === char) { return idx; } return -1; }) .filter(element => element !== -1); } const str = 'hello world'; const indexes = findIndexes(str, 'l'); console.log(indexes); // ๐Ÿ‘‰๏ธ [ 2, 3, 9 ]

The array contains the all indexes of the character in the string.

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.

Copyright ยฉ 2023 Borislav Hadzhiev