Categories
JavaScript Answers

How to find all indexes of a specified character within a string with JavaScript?

Spread the love

Sometimes, we want to find all indexes of a specified character within a string with JavaScript.

In this article, we’ll look at how to find all indexes of a specified character within a string with JavaScript.

How to find all indexes of a specified character within a string with JavaScript?

To find all indexes of a specified character within a string with JavaScript, we can use the string matchAll method.

For instance, we write

const string = "scissors";
const matches = [...string.matchAll(/s/g)];
const indexes = matches.map((match) => match.index);

to call string.matchAll with a regex to find all instances of 's' in string.

Then we call matches.map with a callback that gets the index property of each match object to get the index of each match in a new array and return it.

Conclusion

To find all indexes of a specified character within a string with JavaScript, we can use the string matchAll method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *