How to extract a substring from a string in string in javascript

In JavaScript we use substring() method to extract a sub string from a string. See in the below:

string.substring(first_index,last_index)

string : is the string from which you want to extract a substring.
first_index : is the number specifying the position of the character at which the substring begins. Index of first character will be 0.
last_index : is the number specifying the position of the character at which the substring ends.  Index of last character will be length-1. This is the optional.

Example:

<html>
 <head><Title>Example</Title></head>
  <body>
    <script ="javascript">
     var str="Welcome to AuthorCode";
     document.write(str.substring(2)+"<br />");
     document.write(str.substring(3,14));
    </script>
  </body>
</html>

The output of the code :

lcome to AuthorCode
come to Aut

How to locate a character in a string

If we want to know the exact position of the any characters within a string in JavaScript then we can use indexOf() method.

With the help of this method we can check for a character or even a small string within the current string, and returns the position at which your character or string begins. indexOf() returns only the first appearance of your character or string.

We can use indexof() method like this:
position = string.indexOf(chr);

indoxof() method starts counting at 0 if it returns 0 then character or string begins at the 1st character. see this:

var str="AuthorCode";
var chrposition = str.indexOf('A');

It returns -1 if the character or string you searched for is not contained within the string.

var str="AuthorCode";
var chrposition = str.indexOf('P');

One more important thing is here that if the character or string you search for occurs more than once, indexOf returns only the first appearance of your character or string.

var str="AuthorCode";
var chrposition = str.indexOf('o');