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