JavaScript string.slice() Method
Shubham Vora
Jan 30, 2023
-
Syntax of JavaScript
string.slice()
Method -
Example Code: Take Both
startindex
andendindex
Values for thestring.slice()
Method -
Example Code: Use Negative Indexes for the
string.slice()
Method
A portion or slice of the input string can be returned using the built-in JavaScript function string.slice()
. The startindex
and endindex
parameters must be specified to get the substring of a string.
Syntax of JavaScript string.slice()
Method
string.slice(startindex, endindex);
Parameters
Parameter | Description |
---|---|
startindex |
The index from which the string should begin. |
endindex |
The index till which the string would end. |
Return
It returns the substring of the supplied string according to the index passed as a parameter.
Example Code: Take Both startindex
and endindex
Values for the string.slice()
Method
const str = "JavaScript is amazing";
let result = str.slice(0, 10);
let result1 = str.slice(14, 21);
console.log(result);
console.log(result1);
Output:
JavaScript
amazing
This code returns the portion of the str
string specified in the result
and result1
parameters of the string.slice()
method.
Example Code: Use Negative Indexes for the string.slice()
Method
const str = "JavaScript is an object oriented programming language";
let result1 = str.slice(-9);
let result2 = str.slice(-30, -21);
console.log(result1);
console.log(result2);
Output:
language
oriented
If startindex
or endindex
values are negative, the indexes are counted backward and -1
denotes the final element.
Author: Shubham Vora