JavaScript lastIndexOf method

JavaScript method insertData() can be used to insert some specific string value to the position which is specified by the user.

JavaScript lastIndexOf method

JavaScript lastIndexOf method


JavaScript method lastIndexOf() is very much similar to the method indexOf() of the string object. It has only one difference that it searches for the very last occurrence of searching pattern and indexOf() method goes for the very first occurrence of searching pattern. It takes two arguments : searching pattern and starting index position. It returns "-1" if no match is found or it fails to find the searching pattern or character. One more important thing to notice here is that it is case sensitive. Following is the syntax for using lastIndexOf() method in JavaScript:






 StringObject.lastIndexOf(SearchCharacter, index);

where searchCharacter is the character or string for which we have to find the last index position and index is the integer value from where to start search ( it is optional ).

Description of code

It is a simple code which illustrates the use of lastIndexOf() method. Here we have taken a string "Welcome to RoseIndia Technologies" on which we have to implement the lastIndexOf() method. To implement it we have created a button which calls the function callLastIndexOf() defined in the JavaScript which finds the position value and shows it in the alert() message. Full code is as follows:

<script type="text/javascript">
function callLastIndexOf(){
var string = new String("Welcome to RoseIndia Technologies");
<div align="center">
<table border="0" width="45%" bgcolor="#800080">
<td width="100%" align="center">
<p align="center"><font face="Comic Sans MS" size="7" color="#FFFFFF">lastIndexOf method</font></td>
Welcome to RoseIndia Technologies<br/>
<input type="button" onclick="callLastIndexOf(); this.disabled='true';
  " value="Last Index of o" />

Output :

click on the button "Last Index of o" to find the last index of character "o" in the displayed string "Welcome to RoseIndia Technologies".

Download Source Code