JavaScript indexOf

Sometimes you want to know the position of a character or sub string from a string so for it you can use indexOf method of string object. indexOf object returns a numeric value (index value) of the character or a sub string from a string which you want to know about. indexOf method required two arguments first is the string which's index you want to know and second argument is optional, it required a numeric value which tell the system from where you want to start search from the string. If whatever string you are searching it is not found in the main string then indexOf function will return -1. The example of indexOf method is mentioned below: Code


<html>
  <head>
    <title>JavaScript indexOf</title>
  </head>

  <body>
    <script language='JavaScript' type='text/Javascript'>
      var myString = 'Hello world, welcome to the world of JavaScript';
      var value;
      value=myString.indexOf('JavaScript');
      alert(value);
    </script>
  </body>
</html>
In above mentioned example we have a string object with name of myString and we have a variable with name of value we store the index of 'JavaScript' sub string in the value variable and show it in an alert message. Below is another example with two arguments of indexOf method. Code

<html>
  <head>
    <title>JavaScript indexOf</title>
  </head>

  <body>
    <script language='JavaScript' type='text/Javascript'>
      var myString = 'Hello world, welcome to the world of JavaScript';
      var value;
      value=myString.indexOf('world', 20);
      alert(value);
    </script>
  </body>
</html>
In above mentioned example indexOf function returns the index value of second 'world' present in the myString string object. Because in the example we have included second argument too which start looking 'world' word from 20th character.