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

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 131
    Comment on it

    JavaScript String indexOf() method : The indexOf() method is used to return the index value of specified string. It will give the index of string comes first from the start. We can also start searching by skipping the number of characters. If value is not matched it will return the -1.

    Syntax of indexOf method:

    string.indexOf(searchvalue, start)
    

    As you can see the first parameter is the search value which you want to search within the string, and the second parameter is optional which is used to start the search from.


    Example of indeOf() method : The first example will search the given value in a string and the second example will search the given value in a string but start the search by skipping given number of characters.

    Example1.html

    <!DOCTYPE html>
    <html>
    <body>
    <p>To search the value "this" in string click on the button.</p>
    <button onclick="showIndex()">search</button>
    <p id="container"></p>
    
    <script>
    function showIndex() {
        var str = "What is the index of this string?";
        var indx = str.indexOf("this");
        document.getElementById("container").innerHTML = indx;
    }
    </script>
    </body>
    </html>
    
    Output : 21
    

    Example2.html

    <!DOCTYPE html>
    <html>
    <body>
    <p>Search the first occurance of the letter "i", starting the search at position 6.</p>
    <button onclick="showIndex()">Try it</button>
    <p id="container"></p>
    
    <script>
    function showIndex() {
        var str = "What is the index of this string?";
        var n = str.indexOf("i", 6);
        document.getElementById("container").innerHTML = n;
    }
    </script>
    
    </body>
    </html>
    
    Output : 12
    

 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: