Please note, this is a STATIC archive of website developer.mozilla.org from November 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

Naši dobrovolníci ještě tento článek do jazyka Čeština nepřeložili. Přidejte se a pomozte nám tuto práci dokončit!

The slice() method extracts a section of a string and returns a new string.

Syntax

str.slice(beginSlice[, endSlice])

Parameters

beginSlice
The zero-based index at which to begin extraction. If negative, it is treated as sourceLength + beginSlice where sourceLength is the length of the string (for example, if beginSlice is -3 it is treated as sourceLength - 3).
endSlice
Optional. The zero-based index at which to end extraction. If omitted, slice() extracts to the end of the string. If negative, it is treated as sourceLength + endSlice where sourceLength is the length of the string (for example, if endSlice is -3 it is treated as sourceLength - 3).

Return value

A new string containing the extracted section of the string.

Description

slice() extracts the text from one string and returns a new string. Changes to the text in one string do not affect the other string.

slice() extracts up to but not including endSlice. str.slice(1, 4) extracts the second character through the fourth character (characters indexed 1, 2, and 3).

As an example, str.slice(2, -1) extracts the third character through the second to last character in the string.

Examples

Using slice() to create a new string

The following example uses slice() to create a new string.

var str1 = 'The morning is upon us.';
var str2 = str1.slice(4, -2);

console.log(str2); // OUTPUT: morning is upon u

Using slice() with negative indexes

The following example uses slice() with negative indexes.

var str = 'The morning is upon us.';
str.slice(-3);     // returns 'us.'
str.slice(-3, -1); // returns 'us'
str.slice(0, -1);  // returns 'The morning is upon us'

Specifications

Specification Status Comment
ECMAScript 3rd Edition (ECMA-262) Standard Initial definition. Implemented in JavaScript 1.2.
ECMAScript 5.1 (ECMA-262)
The definition of 'String.prototype.slice' in that specification.
Standard  
ECMAScript 2015 (6th Edition, ECMA-262)
The definition of 'String.prototype.slice' in that specification.
Standard  
ECMAScript 2017 Draft (ECMA-262)
The definition of 'String.prototype.slice' in that specification.
Draft  

Browser compatibility

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support (Yes) (Yes) (Yes) (Yes) (Yes)
Feature Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support (Yes) (Yes) (Yes) (Yes) (Yes) (Yes)

See also

Štítky a přispěvatelé do dokumentace

 Poslední aktualizace od: eduardoboucas,