slice()
方法提取一个字符串的一部分,并返回一新的字符串。
str.slice(beginSlice[, endSlice])
beginSlice
sourceLength + beginSlice
看待,这里的sourceLength 是字符串的长度
(例如, 如果beginSlice
是 -3 则看作是: sourceLength - 3
)endSlice
slice
会一直提取到字符串末尾。如果该参数为负数,则被看作是 sourceLength + endSlice,这里的 sourceLength 就是字符串的长度(例如,如果 endSlice 是 -3,则是, sourceLength - 3)。返回一个从原字符串中提取出来的新字符串
slice()
从一个字符串中提取字符串并返回新字符串。在一个字符串中的改变不会影响另一个字符串。也就是说,slice
不修改原字符串,只会返回一个包含了原字符串中部分字符的新字符串。
注意:slice()
提取的新字符串包括beginSlice
但不包括 endSlice。
例1:str.slice(1, 4)
提取新字符串从第二个字符到第四个 (字符索引值为 1, 2, 和 3)。
例2:str.slice(2, -1)
提取第三个字符到倒数第一个字符。
slice()
创建一个新的字符串下面例子使用 slice()
来创建新字符串:
var str1 = 'The morning is upon us.';
var str2 = str1.slice(4, -2);
console.log(str2); // OUTPUT: morning is upon u
slice()
传入负值索引下面的例子在 slice()
使用了负值索引:
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. | Standard | Initial definition. Implemented in JavaScript 1.2. |
ECMAScript 5.1 (ECMA-262) String.prototype.slice |
Standard | |
ECMAScript 2015 (6th Edition, ECMA-262) String.prototype.slice |
Standard |
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) |