All Categories

Checking if one string contains another substring - indexOf

Want to search for a substring within a javascript string? The example code below shows how to use the javascript indexOf function to find a substring and its location.

var bigstring = 'The dog was sleeping under the tree';
var substring = 'under';
var loc = bigstring.indexOf(substring);
if(loc >= 0)
	alert('Found substring at location '+loc);
	alert('Did not find substring');

The indexOf function will return -1 if it cannot find the substring, otherwise it will return the location (index) of the substring. Note the function name is case sensitive, only 'indexOf' will work, 'indexof' will not work. Good luck !

About the Author


Most Viewed - All Categories