String slice()
In JavaScript, String.slice()
method is used to find the substring of a string which is defined by a specific start index, and an optional end index.
Syntax
str.slice(start)
str.slice(start, end)
str
is a string.start
is a numberend
is a number
slice()
method slices the given string from given start, to end position, and returns the sliced string.
Examples
1. slice(start) – where substring is defined by only a specific start index in the string.
let name = 'appleisgreat';
let output = name.slice(6);
console.log(output);
2. slice(start) with start as negative number
let name = 'appleisgreat';
let output = name.slice(-8); //negative index means counting from end
console.log(output);
3. slice(start, end) – where substring is defined by a specific start index in the string, and a specific end index in the string.
let name = 'appleisgreat';
let output = name.slice(4, 9);
console.log(output);