IndexOf method

 



* indexOf() method is used to identify a specific word is present in the String and it has 2 parameters. 

* Please note, the text given inside this method will do a Case-Sensitive comparison with the main String. 

* If there is no matching word then it will return "-1". If the given word is matching with the main String then it will return the starting index of the matching word.

For example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
var mainString = 'Top Low';
mainString.indexOf('Low');  //output : 4

var mainString = 'Top Low';
mainString.indexOf('Low',3); //output : 4

var mainString = 'Top Low';
mainString.indexOf('L',3); //output : 4

var mainString = 'Top Low';
mainString.indexOf('L',5); //output : -1 , here we are giving instruction to start searching from Index 5.So there is no matching letter as a result it returned -1.

Application area:
To check for the occurrence of a search string inside a larger string, simply check
whether -1 was returned from .indexOf() method.
1
2
3
function existsInString(stringValue, search) {
    return stringValue.indexOf(search) !== -1;
}

Comments