Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • lastIndexOf() method in JavaScript String

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 147
    Comment on it

    JavaScript String lastIndexOf() method : The lastIndexOf() method returns the index of specified value where it last occurred. If no value is matched then this method returns the -1. As it is string the index starts from 0.

    Syntax of lastIndexOf() method :

    string.lastIndexOf(searchvalue, start) 
    

    The first parameter is the value need to search and second parameter is numeric value or index from where the search will start. The first parameter is required but the second parameter is optional.


    Example of lastIndexOf() method : The first example show you how we can get the last index of the value. And the second example you can start the searching from the given index from right .

    Example1.html

        <!DOCTYPE html>
        <html>
        <body>
        <p>To search the last occurance of a prameter click on button.</p>
        <button onclick="showLastIndexOf()">Try it</button>
        <p id="container"></p>
    
        <script>
        function showLastIndexOf() {
            var str = "This is tough task, can you take this task?";
            var lastIndex = str.lastIndexOf("task");
            document.getElementById("container").innerHTML = lastIndex;
        }
        </script>
        </body>
        </html>
    
    Output : 38
    

    Example2.html

    <!DOCTYPE html>
    <html>
    <body>
    <p>To search the last occurrence of a parameter and start search from given position, click on button.</p>
    <button onclick="showLastIndexOf()">search</button>
    <p id="container"></p>
    
    <script>
    function showLastIndexOf() {
        var str = "This is tough task, can you take this task?";
        var lastIndex = str.lastIndexOf("task", 25);
        document.getElementById("container").innerHTML = lastIndex;
    }
    </script>
    </body>
    </html>
    
    Output : 14
    

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: