slice()

ES3+

Extracts a section of a string and returns it as a new string.

Syntax

string.slice(beginIndex, endIndex)

Parameters

beginIndex number

The index at which to begin extraction

endIndex number optional

The index before which to end extraction

Return Value

string

A new string containing the extracted section

Examples

JavaScript
const str = 'Hello World';
console.log(str.slice(0, 5));
console.log(str.slice(-5));
Output:
// 'Hello' 'World'

Related Methods