Find the index of a string within a string with Javascript

Posted in Javascript -

This post looks at how to find the position of a character or a string within a string with Javascript using the indexOf function.

In the Javascript examples below, we'll use the variable "foo" which has been defined as follows:

var foo = "foo bar baz bat";

The indexOf function is a method of the String object, so to find the position of a string within the "foo" variable above we would use foo.indexOf(). This returns an integer value where 0 is the first character in the string. If the string to look for is not found, -1 is returned.

If we were looking for the letter "f" in foo we would do this:

foo.indexOf("f");

We might assign this to a variable (var x = foo.indexOf("f")), output it to the page (document.write(foo.indexOf("f")), show it in a popup window (window.alert(foo.indexOf("f")) etc. The above example would return 0, because "f" is found in the first position of foo and counting starts from 0.

If we wanted to find the position of "bar" in foo, we'd do this:

foo.indexOf("bar");

This would return 4.

If we wanted to look for the position of "b" in foo, we'd do this:

foo.indexOf("b");

This also returns 4. Note that indexOf returns the first instance of the string within the string. So although there are other instances of the letter "b" in foo it will return the first instance only. If we wanted to find subsequent instances of "b" in foo we can pass a second parameter to the indexOf function to specify which character to start from.

Because the first "b" was at index 4, we need to start looking again from index 5, like so:

foo.indexOf("b", 5)

This would return 8. Note that if we'd specified 4 as the second parameter it would return 4.

The final Javascript example below looks for each position of "b" in foo until it reaches the last one:

var pos = foo.indexOf("b");
while(pos > -1) {
    document.write(pos + "<br />");
    pos = foo.indexOf("b", pos+1);
}

This outputs:

4
8
12

Note that in order to prevent being stuck in an infinite loop you must add 1 to the "pos" variable each time indexOf is called in the loop otherwise it will keep return the same position value.



Related posts:


Comments