Advertisement
Web Developer Resources
You Are Here: ESQSoft.com ¬ javascript ¬ methods ¬ JavaScript IndexOf Method
E.S.Q. Software Logo

JavaScript: IndexOf sanity check

IndexOf returns the position in a data type or structure where the first occurence of a passed-in argument appears. If no occurence is found, it returns "-1". Before embracing regular expressions, I used this heavily for assessing strings. However, a friend reminded me recently that this method works with arrays as well as strings** With an array, the method returns the index of the array item where the value occurs. In a string, it's the character position.

Here's the caveat...it doesn't appear to work in IE.

Here's a quick test to demonstrate how it works (or fails) in your browser of choice...

Examples:

<script> function testArray(){ var arr = [ 111, 222, 333 ]; var msg = ''; /* access the 1st element, then find it's position in the array via indexOf */ alert(arr[0]); /* 111 */ alert(arr.indexOf(111)); /* 0 */ /* access an element, then find it's position in the array via indexOf */ alert(arr[2]); /* "333" */ alert(arr.indexOf(333)); /* 2 */ /* failure: attempt to accesses something that doesn't exist in the array */ alert(arr[10]); /* undefined */ alert(arr.indexOf(999)); /* -1 */ } </script>
<script> function testString(){ var str = 'This is a test string'; alert(str.indexOf('test')); /* 10 */ alert(str.indexOf('fail')); /* -1 */ } </script>