JavaScript lastIndexOf() function returns the last index of specified string from string. See the code snippet:
JavaScript lastIndexOf function Example - 1
<!DOCTYPE html>
<html>
<head>
<title>Welcome to LearnKode - A code learning platform</title>
</head>
<body>
<p>Click the button to locate the last occurance of a specified value.</p>
<button onclick="lastOccurance()">Find the position of string</button>
<p id="sample"></p>
<script>
function lastOccurance() {
var str = "I like learnkode and i love learnkode.";
var n = str.lastIndexOf("learnkode");
document.getElementById("sample").innerHTML = n;
}
</script>
</body>
</html>
JavaScript lastIndexOf() function has 2 parameters one is searched value and the started element. See the code snippet:
JavaScript lastIndexOf function Example - 2
<!DOCTYPE html>
<html>
<head>
<title>Welcome to LearnKode - A code learning platform</title>
</head>
<body>
<p>Click the button to locate the last occurance.</p>
<button onclick="lastOccurance()">Find the position of string</button>
<p id="sample"></p>
<script>
function lastOccurance() {
var str = "i love learnkode.";
var n = str.lastIndexOf("love",2);
document.getElementById("sample").innerHTML = n;
}
</script>
</body>
</html>