javascript

indexOf and lastIndexOf a string in javascript

var str = "Check where grapes found";
str.indexOf("grapes"); //It will return 12 as the index

var str = "grapes are not grapes until found";
str.lastIndexOf("grapes"); // Return last index of 'grapes' in str var

.indexOf() function is used as a string method to check whether a given string exists in a string or not. It will return the index of that matching string in the given string. And will return -1 if the string does not exist in the given string.

.llastIndexOf() method is used to find the last occurrence of a word or sentence in a given string. It will also return -1 if text does not found in the given string

Was this helpful?