IndexOf () Definition and usage
The IndexOf () method returns the position of the first occurrence of a specified string value in a string.
Grammar
Stringobject.indexof (Searchvalue,fromindex)
Parameters:
Searchvalue: Required. Specifies the string value that needs to be retrieved. An optional integer parameter.
Fromindex: Specifies where to start retrieving in the string. Its legal value is 0 to stringobject.length-1. If this argument is omitted, it is retrieved from the first character of the string.
Description
The method will retrieve the string stringobject from beginning to end to see if it contains substring searchvalue. The location at which to begin retrieving is at the fromindex of the string or at the beginning of the string (when no fromindex is specified). If a searchvalue is found, the position of the first occurrence of the Searchvalue is returned. The character position in Stringobject is starting at 0.
Hints and Notes
Note: the IndexOf () method is case-sensitive!
Note: If the string value that you want to retrieve does not appear, the method returns-1.
Instance
In this example, we will make a different search within the "Hello world!" string:
<script type= "Text/javascript" >
var str= "Hello world!";
document.write (Str.indexof ("Hello") + "<br/>");
document.write (Str.indexof ("World"));
</script>
The output of the above code:
0 -1 6
Most uses:
Can be used to determine whether the mailbox is correct, such as
<script type= "Text/javascript" >
if ((Yx.email.value.indexOf (' @ ', 0) ==-1) | | (Yx.email.value.indexOf ('. ', 0) ==-1))
{
Alter ("wrong email address");
Yx.email.focus ();
return false;
}
</script>
JS indexof usage indexof () Definition and usage