Here we will describe how to use the indexOf function in JavaScript. In JavaScript, the indexOf function method returns the character location of the substring that appears for the first time in the String object.
IndexOf function in JavaScript
In JavaScript, the indexOf function method returns the character position of the substring that appears for the first time in the String object.
Usage:
- strObj.indexOf(subString[, startIndex])
-
StrObj is required. String object or text.
SubString is required. The substring to be searched in the String object.
StarIndex is optional. This integer indicates the index in the String object. If it is omitted, It is searched from the beginning of the string.
The indexOf Function Method in JavaScript returns an integer indicating the starting position of the substring in the String object. If no substring is found,-1 is returned. If startindex is negative, startindex is treated as zero. If it is larger than the index at the largest character location, it is regarded as the largest possible index.
The indexOf function performs search from left to right. Otherwise, this method is the same as lastIndexOf.
The following example illustrates how to use the indexOf function method.
- function IndexDemo(str2){
- var str1 = "BABEBIBOBUBABEBIBOBU"
- var s = str1.indexOf(str2);
- return(s);
- }