Return to Kroll Design home page

JavaScript Tutorials

 
« Return

indexOf() method for strings

The indexOf method searches the specified string for the specified substring, and returns the location of the substring, if found. If the substring is not found, indexOf returns a -1. Compare with the lastIndexOf method.

There are two forms of this method. In one form, you add an optional 3rd parameter to specify where to start searching for the substring. This allows you to bypass any beginning section of the string that you don't want to search.

Code:

<script type="text/javascript">
//<![CDATA[
function indexOfFunction(mainString, searchString, startSearchAt) { if (startSearchAt === undefined) startSearchAt = 0; var searchStringLocation = mainString.indexOf(searchString, startSearchAt); document.write("Location of \"", searchString, "\" within \"", mainString, "\" : ", searchStringLocation, "<br>"); } myString = "catcat"; document.write(myString.indexOf("at")); document.write("<br>"); document.write(myString.indexOf("at",3)); // start searching at position 3 document.write("<br>"); indexOfFunction("This is how to do it.", "is"); indexOfFunction("This is how to do it.", " is"); indexOfFunction("012.121", "2", 3); indexOfFunction("This is how to do it.", "bla"); //]]> </script>

Output:



 
« Return


©2012 Kroll Design    info@KrollDesign.net    781.910.3694
Last modified: 12/31/1969 7:00 PM