The method slice( ) extracts the text from one string and returns a new string with the extracted text. There is no change to the original variable unless of course the method is applied to itself. This is the same as taking a slice of cake but the cake stays intact. We must give this copy of sliced cake to another variable in order to reuse it.
This method uses up to two parameters. The first parameter indicates the zero based first character to be sliced (copied from). The second parameter indicates the first character to be excluded from the action of slicing. (included from, excluded from).
1- Declare a variable:
var xpt = "red,blue,white,black";
2- Extracting the word “blue” into another variable:
var xpt = "red,blue,white,black"; var xpt2 = xpt.slice(4,8);
3- Call xpt2;
It returns “blue”. The first character to be included is on position 4 ( as in 0,1,2,3,4), and the first to be excluded is on position 8, which is the comma.
Using negative numbers:
As an alternative, if we apply a negative number to the second parameter, it changes its meaning: now it means to start excluding from the right, based on the number of characters indicated. Commas and spaces count as characters.
4- For example: excluding the last color (black and the comma to its left) from our slicing):
var xpt = "red,blue,white,black"; var xpt3 = xpt.slice(0,-6);
5- Call the variable: xpt3;
It returns “red, blue, white”. In other words, it includes all characters from position zero on, except the last 6 from the end. This also means that we could exclude some characters from the extreme left, if instead of zero we entered some other number as the left parameter.
Using just one parameter:
When using just one positive parameter, this parameter represents the first character position to be included on the slice which extends all the way to the end.
1- For example:
var xpt = "red,blue,white,black"; var x = xpt.slice(3);
// returns “,blue,white,black”, which means that “red” was cutoff.
var xpt = "red,blue,white,black"; var x = xpt.slice(-3);
// it returns “ack” from “black”. It counted from the right to the left 3 characters and cutoff all the others at the left.
3- One more example. Extract the “e” from ecmascript:
// returns “cmascript”.
This is actually useful to remove the first character and replace it with another similar character capitalized, as we will see later in the eBook