1. Home
  2. Computing & Technology
  3. JavaScript

indexOf

Join the Discussion

Questions? Comments?

The indexOf method is the simplest way to determine if a text string contains a particular character or group of characters. The simplest way to describe how it works is to look at an example.

var mystring = 'the wheels on the bus';
var toFind = 'wheel';
alert(mystring.indexOf(toFind));

In this example mystring is the text string that we want to test and toFind is the text that we want to search for. The alert box will tell us what the indexOf method returns as a result of the search (4 in this example).

The method actually returns the position where the string to find starts in the string being searched (the first position is 0 so wheel starts in position 4). If the string can't be found at all then -1 is returned making it easy to test if the text is found using:

if (mystring.indexOf(toFind) != -1) alert('found');

indexOf locates the first occurrence of the text within the string, if you need the last occurrence instead then you can use lastIndexOf in exactly the same way.

Explore JavaScript
About.com Special Features

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

Easy ways to connect two computers for networking purposes. More >

  1. Home
  2. Computing & Technology
  3. JavaScript

©2009 About.com, a part of The New York Times Company.

All rights reserved.