JavaScript(JS) string method - slice
The slice()
method is a string method in JavaScript that is used to extract a portion of a string and return it as a new string.
Here is the syntax for the slice()
method:
str.slice(startIndex, endIndex)
Here, str
is the string you want to extract a portion of, startIndex
is the index where the extraction should start, and endIndex
is the index where the extraction should end (but not include).
The slice()
method returns a new string that consists of the portion of the str
starting at the startIndex
and ending at the endIndex
.
If the endIndex
is not specified, the slice()
method extracts all characters from the startIndex
to the end of the string.
Here is an example of using the slice()
method:
let str = "hello world"; let result = str.slice(6, 11); console.log(result); // "world"
In the example above, the slice()
method extracts the characters from index 6 to index 11 (but not include) from the str
, which is the string "world".
If the startIndex
or endIndex
is negative, it is treated as an offset from the end of the string. For example, if startIndex
is -3, the extraction will start at the 3rd character from the end of the string. If endIndex
is negative, the extraction will end at the nth character from the end of the string.
Here is an example of using the slice()
method with negative indices:
let str = "hello world"; let result = str.slice(-5); console.log(result); // "world"
In the example above, the slice()
method extracts all characters from index -5 to the end of the string. Since -5 is an offset from the end of the string, it starts from the character "w". The resulting string is "world".