JavaScript, how to find a character in a string
By Flavio Copes
Learn how to find a character in a string in JavaScript using includes() to check if it is present and indexOf() to get the position of the first occurrence.
How do you find a character in a string, using JavaScript? Use includes() to know if the character is there, and indexOf() to know where it is.
Which one you pick depends on the question you’re asking. Let’s look at both.
Checking if the character exists
Every string has an includes() method that accepts one (or more) characters.
This method returns true if the string contains the character, and false if not:
'a nice string'.includes('a') //true
'a nice string'.includes('b') //false
This is the method I reach for most often, because most of the time the question is just “is it in there?”.
Finding the position
If you need to find the exact position of the letter in the string, however, you need to use the indexOf() method:
'a nice string'.indexOf('a') //0
'a nice string'.indexOf('c') //4
If there are more than one occurrence, this method returns the position of the first one it finds, starting from the left.
When the character is not in the string at all, indexOf() returns -1:
'a nice string'.indexOf('z') //-1
You can also pass a second argument to start searching from a given position. This is how you find the second occurrence of a character:
'a nice string'.indexOf('n') //2
'a nice string'.indexOf('n', 3) //11
The first call finds the n in “nice”. The second starts looking from position 3, so it skips it and finds the n in “string”.
If you want the last occurrence instead, there’s lastIndexOf(), which searches from the right.
Both methods are case sensitive
One thing to keep in mind: these searches distinguish uppercase from lowercase.
'Rome'.includes('r') //false
If you want a case insensitive search, lowercase both sides first, with toLowerCase().
A classic pitfall with indexOf()
Be careful using indexOf() inside a condition. This code looks fine, but it’s broken:
const city = 'amsterdam'
if (city.indexOf('a')) {
//do something
}
The a is at position 0, and 0 is a falsy value. So the condition is false even though the character exists. Even worse, when the character is missing, indexOf() returns -1, which is truthy, and the condition passes.
The fix: compare explicitly with city.indexOf('a') !== -1, or better, use includes(), which returns a real boolean and says what you mean.
Related posts about js: