The substring() Function is used to slice a substring from the given String. It doesn't accept negative indexes.
Say, you have a String Hello and you want to take ell from the String Hello and store it in a different variable.
<html> <body> <script> var x = "Hello" var y = x.substring(1,4) document.write(y) </script> </body> </html>
So, we want to take the chunk of letters/characters from the String Hello and store it into the variable y.
And in the first line, we have stored Hello inside x.
x = "Hello"
Also, let us see the elaborated structure.
So, we want to take the chunk ell from Hello. And that happens in the next line.
var y = x.substring(1,4)
Just note, the position of e from ell is 1 and the position of the last l from ell is 3.
So, the statement, x.substring(1,4) picks the value from position 1 till the position of the l plus 1. i.e. The position of second l is 3. We just add 1 to it.
So, the statement x.substring(1,4) simply refers, "Pick the chunk from position 1 to position (4-1)".
And ell is assigned to the variable y.
And in the next line, we have the print statement,
document.write(y)
That prints the chunk of letters ell.
Again let us see, how can wee access the last 3 letters of the string i.e. llo.
<html> <body> <script> var x = "Hello" var y = x.substring(2) document.write(y) </script> </body> </html>
There is a speciality of substring().
Say for example, by mistake you have given the opposite range to extract.
i.e.
<html> <body> <script> var x = "Hello" var y = x.substring(4,1) document.write(y) </script> </body> </html>
Although we have given the opposite range to extract.
var y = x.substring(4,1)
But JavaScript makes an intelligent guess and extracts ell.