String.prototype.slice()

This translation is incomplete. Please help translate this article from English.

El mètode slice() extreu una secció d'una cadena i retorna una nova cadena.

Sintaxi

str.slice(beginSlice[, endSlice])

Paràmetres

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).

Descripció

slice() extreu el text d'una cadena i retorna una nova cadena. Els canvis fets en el text d'una cadena no afecten l'altra cadena.

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.

Exemples

Utilitzar slice() per crear una nova cadena

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

Utilitzar slice() amb índexs negatius

El següent exemple utilitza slice() amb índexs negatius.

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

Especificacions

Especificació Estat Comentaris
ECMAScript 3rd Edition (ECMA-262) Standard Definició inicial. Implementat en 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  

Compatibilitat amb navegadors

Característica Chrome Firefox (Gecko) Internet Explorer Opera Safari
Suport bàsic (Yes) (Yes) (Yes) (Yes) (Yes)
Característica Android Chrome per Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Suport bàsic (Yes) (Yes) (Yes) (Yes) (Yes) (Yes)

Vegeu també

Document Tags and Contributors

 Contributors to this page: llue
 Last updated by: llue,