The slice() method extracts a section of a string and returns it as a new string, without modifying the original string.
str.slice(beginIndex[, endIndex])
beginIndexstrLength + beginIndex where strLength is the length of the string (for example, if beginIndex is -3 it is treated as strLength - 3). If beginIndex is greater than or equal to the length of the string, slice() returns an empty string.endIndexendIndex is omitted, slice() extracts to the end of the string. If negative, it is treated as strLength + endIndex where strLength is the length of the string (for example, if endIndex is -3 it is treated as strLength - 3).A new string containing the extracted section of the string.
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 endIndex. 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.
slice() to create a new stringThe following example uses slice() to create a new string.
var str1 = 'The morning is upon us.', // the length of str1 is 23.
str2 = str1.slice(1, 8),
str3 = str1.slice(4, -2),
str4 = str1.slice(12),
str5 = str1.slice(30);
console.log(str2); // OUTPUT: he morn
console.log(str3); // OUTPUT: morning is upon u
console.log(str4); // OUTPUT: is upon us.
console.log(str5); // OUTPUT: ""
slice() with negative indexesThe 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'
| 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 Latest Draft (ECMA-262) The definition of 'String.prototype.slice' in that specification. | Draft |
| Desktop | ||||||
|---|---|---|---|---|---|---|
| Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | |
| Basic support | Yes | Yes | 1 | Yes | Yes | Yes |
| Mobile | |||||||
|---|---|---|---|---|---|---|---|
| Android webview | Chrome for Android | Edge Mobile | Firefox for Android | Opera for Android | iOS Safari | Samsung Internet | |
| Basic support | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
| Server | |
|---|---|
| Node.js | |
| Basic support | Yes |
© 2005–2018 Mozilla Developer Network and individual contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/slice