Checking to See If a String Contains a Substring

var s1 = "I think therefore I am"; var a = s1.indexOf("think");     // a = 2 var b = s1.indexOf("thought"); // b = -1

The simplest way to check to see if one string is a substring of another is to use .indexOf(substring) on the main string. This function returns an index of the location of the first occurrence, or –1 if the substring is not found.

Get jQuery and JavaScript Phrasebook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.