Microsoft® JScript™
indexOf Method
 Language Reference 
Version 1 

See Also                  Applies To


Description
Finds the first occurrence a substring within a String object.
Syntax
strVariable.indexOf(substring, startindex)
"String Literal".indexOf(substring, startindex)

The indexOf method syntax has these arguments:

Part Description
substring The substring to search for within the String object.
startindex An optional integer value specifying the index to begin searching within the String object. If omitted, searching begins at the beginning of the string.

Remarks
The indexOf method returns an integer value indicating the beginning of the substring within the String object. If the substring is not found, a -1 is returned.

You might try to use this to test if a substring is present in a string, but note that -1 is NOT false (0 is) so text.indexOf("t") is false if the first character in the string is "t" but true if the second (or following) character is "t" and it is true if "t" is not found in the string.

if ("test".indexOf("t")) {console.log("true")}
undefined
if ("test".indexOf("e")) {console.log("true")}
true
if ("test".indexOf("z")) {console.log("true")}
true

Effectively, string.indexOf(substring) returns false if and only if string starts with substring. So !string.indexOf(substring) actually returns true if string starts with substring! The opposite of what you might expect.

Turns out when used with a number, the Tilde operator (bitwise not) effective does ~N => -(N+1) . This expression evaluates to 0 only when N == -1. We can leverage this by putting ~ in front of the indexOf(...) function to do a boolean check if an item exists in a String or an Array.

if (~strvar.indexOf(substring)) { //substring was found 
if (!~strvar.indexOf(substring)) { //substring was NOT found 

If startindex is negative, startindex is treated as zero. If it is larger than the greatest character position index, it is treated as the largest possible index.

Searching is performed from left to right. Otherwise, this method is identical to lastIndexOf.


© 1997 by Microsoft Corporation. All rights reserved.

Comments: