JavaScript slice() Method returns a part of a string from start position to end position.
Positions are index values of characters in a string. From left counting starts from 0 while from right it starts from -1. Remember that element placed at the end position is not included in the return string.
Let's have a variable named text and we will assign a string to it. slice() method will return characters from 0 index position to character which is at 3rd position because 4th one is not included.
let text = 'HowToCodeSchool';
let string = text.slice(0,4);
document.getElementById('output').innerHTML = 'Output: ' + string;
Output: HowT
If we only assign one index value then whole string from that position is returned.
let text = 'HowToCodeSchool';
let string = text.slice(4);
document.getElementById('output').innerHTML = 'Output: ' + string;
Output: oCodeSchool
In case of negative values the counting is done from right side. If only one negative number is assigned then whole string from that number is returned.
let text = 'HowToCodeSchool';
let string = text.slice(-4);
document.getElementById('output').innerHTML = 'Output: ' + string;
Output: hool
Video Tutorial
Watch video tutorial on JavaScript slice() Method.