เมธอดนี้คืนค่าดัชนีภายในอ็อบเจ็กต์ String ที่เรียกของค่าที่ระบุครั้งสุดท้าย โดยเริ่มต้นการค้นหาที่ fromIndex หรือ -1 หากไม่พบค่า
ไวยากรณ์
ต่อไปนี้คือรูปแบบ −
string.lastIndexOf(searchValue[, fromIndex])
นี่คือพารามิเตอร์ -
- searchValue − สตริงที่แสดงค่าที่จะค้นหา
- fromIndex − ตำแหน่งภายในสตริงการโทรเพื่อเริ่มการค้นหา อาจเป็นจำนวนเต็มใดๆ ระหว่าง 0 ถึงความยาวของสตริง ค่าเริ่มต้นคือ 0
ตัวอย่าง
คุณสามารถลองเรียกใช้โค้ดต่อไปนี้เพื่อเรียนรู้วิธีรับดัชนีของค่าที่ระบุในสตริงที่เกิดขึ้น -
<html>
<head>
<title>JavaScript String lastIndexOf() Method</title>
</head>
<body>
<script>
var str1 = new String( "Learn for free and enjoy! Learn and share!" );
var index = str1.lastIndexOf( "Learn" );
document.write("lastIndexOf found String :" + index );
document.write("<br />");
var index = str1.lastIndexOf( "and" );
document.write("lastIndexOf found String :" + index );
</script>
</body>
</html>