Home »
JavaScript
String lastIndexOf() Method with Example in JavaScript
JavaScript String lastIndexOf() Method: Here, we are going to learn about the lastIndexOf() method of String in JavaScript.
Submitted by IncludeHelp, on February 02, 2019
String lastIndexOf() Method
lastIndexOf() is method is a String method, it is used to check whether a substring exists in the given string or not. It returns the last index of the substring from the string where substring exists. If substring does not exist in the string – it returns -1.
Syntax
String.lastIndexOf(substring, [offset]);
Here, substring is the part of the string to be searched and [offset] is the specific index from where we want to search the substring, it's an optional parameter and it's default value is 0.
Note: Method lastIndexOf() searches backward in the string, see in the example – we passed offset 15 and it returns index 0.
Example
<html>
<head>
<title>JavaScipt Example</title>
</head>
<body>
<script>
var str = "Hello friends say Hello";
var substr = "Hello";
var index = str.lastIndexOf(substr);
if(index!=-1)
document.write(substr + " found at " + index + " position.<br>");
else
document.write(substr + " does not exist in the " + str + ".<br>");
substr = "Hi";
index = str.lastIndexOf(substr);
if(index!=-1)
document.write(substr + " found at " + index + " position.<br>");
else
document.write(substr + " does not exist in the " + str + ".<br>");
//searching from a specific index
substr = "Hello";
index = str.lastIndexOf(substr,10);
if(index!=-1)
document.write(substr + " found at " + index + " position.<br>");
else
document.write(substr + " does not exist in the " + str + ".<br>");
substr = "friends";
index = str.lastIndexOf(substr,15);
if(index!=-1)
document.write(substr + " found at " + index + " position.<br>");
else
document.write(substr + " does not exist in the " + str + ".<br>");
</script>
</body>
</html>
Output
Hello found at 18 position.
Hi does not exist in the Hello friends say Hello.
Hello found at 0 position.
friends found at 6 position.
JavaScript String Object Methods »