Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

String.prototype.slice — extracting part of a string

String.prototype.slice returns part of a string from start inclusive to end exclusive without changing the original. Negative indices count from the end, and omitting end extracts the rest of the string.

Version: ECMAScript and Web APIs; exact feature edition and browser support reviewed per entry; Node 24 in repository does not prove browser API support

Syntax

text.slice(start, end)

String.prototype.slice returns a primitive string value without changing the original. In text.slice(start, end), indices are zero-based: start is included and end is excluded. Omitting start means 0; omitting end or passing undefined means the string length. Calling text.slice() returns the entire string.

A negative index is relative to the end: -1 identifies the last code unit. After adjustment, indices are clamped between 0 and the string length. If the start equals or exceeds the end, the result is "". Unlike substring, slice does not swap the boundaries.

Index arguments undergo numeric conversion; fractional parts are truncated toward zero, and NaN becomes 0. Indices refer to UTF-16 code units, not user-perceived characters. Slicing can therefore split a surrogate pair or a sequence forming one visible character.

This is an ECMAScript standard method, not a Web API. It can be borrowed using String.prototype.slice.call(value, start, end): the receiver is converted to a string, but null and undefined cause a TypeError.

Examples

const text = "JavaScript";
console.log(text.slice(0, 4));
console.log(text.slice(4));
console.log(text.slice(-6, -2));
console.log(JSON.stringify(text.slice(7, 2)));
console.log(text);

Result

Java
Script
Scri
""
JavaScript

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources