JavaScript LogoThe JavaScript indexOf() method allows you to find out if a string contains one or more characters, and if so, the starting position of that set of characters

If you’ve ever found yourself saying: “How do I figure out if one string contains a certain character or a sub-string?” then the JavaScript indexOf() method is for you. It returns the starting position of a string, even if it is one character. If that string does not exist, then it returns “-1”. So, if you want to know if a given string even exists at all in another string, simply test to see whether or not the JavaScript method indexOf() returns “-1”. If it does, then the sub-string does not exist. If the return value is “> -1” (i.e. more than -1), then the string does exist.

Example # 1

In Example # 1, we check for the starting position of “football” within the string “Hello world”. Because “football” does not exist in “Hello world”, the return value is “-1”

Example # 2

In Example # 2, we use an “if else” condition to test for the string “football” in “hello world”. In this case, it does not exist.

Example # 3

In Example # 3, we have included the string “football” in “hello world”, so the test returns the starting value of “football”, which is “6”. So, the test evaluates to “true”, the “true” text is displayed, and at the end of that text, we return the starting position of “football”.


The JavaScript indexOf() method is the best way to find out if one string exists inside of another. If it does, the starting position of that searched string is returned. If the sub-string does not exist, then “-1” is returned; this is  a reliable indicator of “does not exist”.

Helpful links for the JavaScript indexOf() method