Computer >> Computer tutorials >  >> Programming >> Javascript

How to get the first index of an occurrence of the specified value in a string in JavaScript?


To get the first index of an occurrence of the specified value in a string, use the JavaScript indexOf() method.

Example

You can try to run the following code to get the first index −

<html>
   <head>
      <title>JavaScript String indexOf() Method</title>
   </head>

   <body>
      <script>
         var str = new String( "Learning is fun! Learning is sharing!" );
         var index = str.indexOf( "Learning" );
         document.write("First index of string Learning :" + index );
      </script>
   </body>
</html>