Locating a character in a string:
indexOf and lastIndexOf methods

JavaScript FAQ | JavaScript Strings and RegExp FAQ  

Question: How do I locate the position of a given character in a string variable?

Answer: To determine the position of a given character c (or a given substring c) within a string, use the JavaScript string.indexOf() method, like this:

pos = string.indexOf(c);
For example, if you want to find the position of the character '1' or '.' within the string '123.4567', this can be accomplished with the following code:
str = '123.4567';
pos1 = str.indexOf('1');  // Result: 0
pos2 = str.indexOf('.');  // Result: 3
Note that string.indexOf() uses zero-based character numbering, that is, for the very first character in the string, the string.indexOf() method returns index 0; for the second character, it returns 1, and so on. If you prefer character numbering starting with 1 rather than 0, then, instead of the above example you could use
pos = 1+str.indexOf(c)
If there are two or more occurrences of the character (or substring) c within string, then string.indexOf(c) will return the index of the first occurrence. Use the string.lastIndexOf(c) method if you need the last occurrence rather than the first one.

If you want the index of the character (or substring) c within a portion of the given string starting at position start, you can use the following:

pos = string.indexOf(c,start);      // first occurrence after start
pos = string.lastIndexOf(c,start);  // last occurrence after start

If the given character is not found, then string.indexOf() as well as string.lastIndexOf() will return -1.

Copyright © 1999-2011, JavaScripter.net.