Skip to content
Home ยป JS: indexOf() Method

JS: indexOf() Method

    The JavaScript string has some of the properties of array. You may access a character of the string using index.

    In order to find the correct index of a character , you can use <span style="color:#a31d00" class="tadv-color">indexOf()</span> method of string class.

    Here is an example program to demonstrate the usage of this method.

    <!DOCTYPE html>
    <html>
    <head>
       <title>JS: indexOf Method</title>
       <meta charset="utf-8">
    </head>
    <body>
    <script>
    var answer = "Lion is the king of Jungle!";
    var res = answer.indexOf('king');
    console.log(res);
    //output = 12
    </script>
    </body>
    </html>

    The above program will result in 12. The array or string index always start at 0 in JavaScript programming.

    The substring ‘king’ starts at index 12. The script goes through all the characters one-by-one and finally reaches the character ‘k’ which is at index 12.