Menu Home

indexOf()

Hi everybody, and welcome to another exciting edition of Boring JavaScript. Today, we cover the indexOf() method, for both the String and the Array.

Don’t want to read? Check out our video!

Where, Oh Where, Has My Little String Gone?

For both Strings and Arrays, the indexOf() method finds the first occurrence of a string within the String or the Array, and will return the position of that string within the target String or Array.

Let’s look at Strings first:

const animals = "Cat,Dog,Horse,Cow,Coyote,Road Runner,Dolphin,Whale,Lizard";

const whereIsMyCat = animals.indexOf("Cat");
const whereIsMyHorse = animals.indexOf("Horse");
const whereIsMyDinosaur = animals.indexOf("Dinosaur");
const whereIsMyOtherCat = animals.indexOf("cat");

console.log(`\nMy Cat is at position ${whereIsMyCat}`);
console.log(`My Horse is at position ${whereIsMyHorse}`);
console.log(`My Dinosaur is at position ${whereIsMyDinosaur}`);
console.log(`My Other Cat is at position ${whereIsMyOtherCat}`);

Lines 3, 4, 5, and 6 contain the indexOf() method. It is performed upon a target string (in our case the variable ‘animals’), and takes one argument, a search string. JavaScript will then take that search string and … well … search the target string for the first occurrence of the search string. It will return one of two values:

  1. 0 – Length of the target string minus 1: This is the character position of the search string within the target string. It will always be the position of the first character in the search string. (Remember: the position of characters inside strings always start counting at 0);
  2. -1: If the string could not be found.

In our example above, the variable “whereIsMyCat” will return 0, since the search string “Cat” will be found beginning at position 0 in the target string.

The variable “whereIsMyHorse” will return 8, since the string “Horse” appears in the target string starting at position 8.

The last two variables – ‘whereIsMyDinosaur’ and ‘whereIsMyOtherCat’ will both return -1, meaning that the strings could not be found. Why? For ‘whereIsMyDinosaur’, it’s simple: The string ‘dinosaur’ does not appear in the target string. But ‘cat’ does, right? No, it does not. The method indexOf() is case sensitive, meaning that ‘Cat’ and ‘cat’ are two different strings (one has an upper-case ‘C’ while the other has a lower-case ‘c’). And if you look at the target string, you’ll notice that none of the animal names start with a lower-case. Therefore, it will never find ‘cat’, and so return a -1.

Cats, Cats, Everywhere.

One thing to remember about indexOf() is that it will return the first occurrence of that string within the target string. What if there was more than one? How do we find those occurances?

Easy! We can use the optional second argument to indexOf(), and that is the ‘fromIndex’. This second argument tells JavaScript what index (or position) number within the string to start searching. If the argument is not present (as it wasn’t in our examples above), then the default is 0, or ‘start at position 0’.

Let’s expand our string and take a look how we can use indexOf() to count the number of occurrences of a string within our target string.

const animals = "Cat,Dog,Horse,Cow,Coyote,Road Runner,Dolphin,Whale,Lizard,Cat,Dog,Horse,Cow,Cat,Whale";

let myCatCount = 0;
let catIndex = animals.indexOf('Cat');

while (catIndex !== -1) {
	myCatCount ++;
	catIndex = animals.indexOf('Cat', catIndex + 1);
}

console.log(`\nI have ${myCatCount} cats.`);

Running the above code will output a total of 3 cats. We use the first indexOf in line 5 to find our first ‘Cat’ (which will be position 0). That will get saved in the variable ‘catIndex’. Then we keep executing Lines 8 and 9 within the while loop, incrementing ‘myCatCount’ for each loop, then, importantly, using ‘catIndex + 1’ as our starting ‘fromIndex’ for the next iteration.

This means the values of ‘catIndex’ will be as follows:

  1. First time through: 0
  2. Second time through: 59
  3. Third time through: 77
  4. Fourth time through: -1

Since we only made it three times through until ‘catIndex’ became -1, we have three cats.

An Array of Cats

What about Arrays? Amazingly – and thankfully – they work the exact same way as strings. Seriously. I can take the code above, change the target string to a target array, and everything will work exactly the same.

Instead of looking at character positions in a string, now JavaScript is looking at index entries within an array.

const animals = [
	"Cat", "Dog", "Horse", "Cow", "Coyote", "Road Runner", "Dolphin", "Whale", "Lizard"
];

const whereIsMyCat = animals.indexOf("Cat");
const whereIsMyHorse = animals.indexOf("Horse");
const whereIsMyDinosaur = animals.indexOf("Dinosaur");
const whereIsMyOtherCat = animals.indexOf("cat");

console.log(`\nMy Cat is at position ${whereIsMyCat}`);
console.log(`My Horse is at position ${whereIsMyHorse}`);
console.log(`My Dinosaur is at position ${whereIsMyDinosaur}`);
console.log(`My Other Cat is at position ${whereIsMyOtherCat}`);

And instead of using the second argument of indexOf() to start at a character position, we now start at an index number within the array:

const animals = [
    "Cat", "Dog", "Horse", "Cow", "Coyote", "Road Runner", 
    "Dolphin", "Whale", "Lizard", "Cat", "Dog", "Horse", 
    "Cow", "Cat", "Whale"
];

let myCatCount = 0;
let catIndex = animals.indexOf('Cat');

while (catIndex !== -1) {
	myCatCount ++;
	catIndex = animals.indexOf('Cat', catIndex + 1);
}

console.log(`\nI have ${myCatCount} cats.`);

As you can see, indexOf() works the exact same way for Arrays as it does for String.

The Video

As always, check out our YouTube video on this subject. And make sure you subscribe!

Shameless Plugs

We’re everywhere!

Facebook

YouTube

Twitter

Categories: Boring JavaScript Javascript

Tagged as:

thevirtuoid

Web Tinkerer. No, not like Tinkerbell.

Creator of the game Virtuoid. Boring JavaScript. Visit us at thevirtuoid.com

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: