The slice() method extracts and returns a section of a string.
Example
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
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.
Output
language. language
Recommended Reading: Javascript String substring()