In JavaScript, the indexOf()
method takes a string and a substring and returns the starting index of the first occurrence of the given substring in that string.
str.indexOf(substr, startIndex);
str: String in which the substring substr
is searched.
substr: Substring whose position is searched in given string str
.
startIndex: Starting index for the search. If no startIndex
is provided, the search starts at the 0th index.
Return Value: Returns the start index of the first occurrence of the substr
in str
or returns -1 (if no occurrence found).
As shown in Line 1 and 5, the indexOf()
method is case-sensitive. The same fact is justified by Line 6, where on searching “B”, -1 is returned since only the lowercase forms of the alphabet exist in the given string.
console.log('To be or not to be'.indexOf('To'));console.log('To be or not to be'.indexOf(' '));console.log('To be or not to be'.indexOf('o', 2));console.log('To be or not to be'.indexOf('be', 4));console.log('To be or not to be'.indexOf('to'));console.log('To be or not to be'.indexOf('B'));console.log('To be or not to be'.indexOf('', 9));
Free Resources