The slice()
method extracts and returns a section of a string.
Example
const message = "JavaScript is fun";
// slice the substring from index 0 to 10
let result = message.slice(0, 10);
console.log(result);
// Output: JavaScript
slice() Syntax
The syntax of the slice()
method is:
str.slice(beginIndex, endIndex)
Here, str
is a string.
slice() Parameters
The slice()
method takes in:
beginIndex
- Starting index of the selectionendIndex
(optional) - Ending index of the selection (Exclusive) By default, it extracts till the end of the string.
slice() Return Value
- Returns a new string containing the extracted section of the string.
Note: The slice()
method does not change the original string.
Example 1: Using slice() method
const str = "JavaScript is a very absurd programming language.";
// from index 28 to end
console.log(str.slice(28)); // 'programming language.'
// from index 4 to 14
console.log(str.slice(4, 15)); // 'Script is a'
Output
programming language. Script is a
Example 2: Using slice() method with negative indices
If beginIndex
or endIndex
are negative, the values are counted from backward. For example, -1 represents the last element, -2 represents the second-to-last element and so on.
const str = "JavaScript is a very absurd programming language.";
// from 9th to last element till end
console.log(str.slice(-9)); // 'language.'
// from 9th to last element to 2nd to last element
console.log(str.slice(-9, -1)); // 'language'
Output
language. language
Recommended Reading: Javascript String substring()