The slice() Function is used to slice a substring from the given String. Also accepts 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.slice(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.slice(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.slice(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.slice(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.
Let us rewrite the above code using the negative positions.
<html> <body> <script> var x = "Hello" var y = x.slice(-4,-1) document.write(y) </script> </body> </html>
The same way, we have accessed ell from Hello using negative indexes.
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.slice(2) document.write(y) </script> </body> </html>