extraction

String.prototype.slice

Extracts a section of the string from beginIndex up to but not including endIndex, returning a new string. Negative indices count from the end.

str.slice(beginIndex[, endIndex])

Parameters

Parameter Purpose
beginIndex Start position (negative counts from end)
endIndex Exclusive end position (default str.length; negative counts from end)

Examples

console.log('hello world'.slice(0, 5));

Prints 'hello'

console.log('hello world'.slice(-5));

Prints 'world'

console.log('hello'.slice(1, -1));

Prints 'ell'

console.log('hello'.slice(3, 1));

Prints '' (end before start)

Gotcha

Unlike substring, slice does NOT swap arguments — if end < start you get an empty string. Negative indices are the main reason to prefer slice over substring.

Related methods

← All JS string methods · JS array methods