试一试
const str = "The quick brown fox jumps over the lazy dog.";
console.log(str.slice(31));
// Expected output: "the lazy dog."
console.log(str.slice(4, 19));
// Expected output: "quick brown fox"
console.log(str.slice(-4));
// Expected output: "dog."
console.log(str.slice(-9, -5));
// Expected output: "lazy"
语法
js
slice(indexStart)
slice(indexStart, indexEnd)
参数
indexStart-
要包含在返回的子字符串中的第一个字符的索引。
indexEnd可选-
要从返回的子字符串中排除的第一个字符的索引。
返回值
包含所提取字符串部分的新字符串。
描述
slice() 方法从一个字符串中提取文本,并返回一个新字符串。
slice() 方法提取到 indexEnd 的前面(不包括 indexEnd)。例如,str.slice(4, 8) 会提取从第五个字符到第八个字符(索引为 4、5、6 和 7 的字符)。
indexStart indexEnd
↓ ↓
| 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
| T | h | e | | m | i | r | r | o | r |
m i r r
_______________
↑
Result
- 如果
indexStart >= str.length,则返回一个空字符串。 - 如果
indexStart < 0,则该索引被视为从字符串末尾开始计算。更正式地说,在这种情况下,子字符串的开始位置为max(indexStart + str.length, 0)。 - 如果
indexStart被省略、为undefined,或者无法被转换为数字,则将其视为0。 - 如果
indexEnd被省略、为undefined,或者indexEnd >= str.length,则slice()方法将提取到字符串的末尾。 - 如果
indexEnd < 0,则该索引被视为从字符串末尾开始计算。更正式地说,在这种情况下,子字符串的结束位置为max(indexEnd + str.length, 0)。 - 如果标准化负值后
indexEnd <= indexStart(即indexEnd代表的字符在indexStart之前),则返回一个空字符串。
示例
使用 slice() 创建新字符串
以下示例使用 slice() 方法创建新字符串。
js
const str1 = "The morning is upon us."; // The length of str1 is 23.
const str2 = str1.slice(1, 8);
const str3 = str1.slice(4, -2);
const str4 = str1.slice(12);
const str5 = str1.slice(30);
console.log(str2); // he morn
console.log(str3); // morning is upon u
console.log(str4); // is upon us.
console.log(str5); // ""
使用 slice() 和负数索引
以下示例使用 slice() 方法和负数索引。
js
const str = "The morning is upon us.";
str.slice(-3); // 'us.'
str.slice(-3, -1); // 'us'
str.slice(0, -1); // 'The morning is upon us'
str.slice(4, -1); // 'morning is upon us'
此示例从字符串末尾倒数 11 个字符来查找起始索引,并从字符串开头正数 16 个字符来查找结束索引。
js
console.log(str.slice(-11, 16)); // "is u"
此处从开头正数 11 个字符来查找起始索引,并从末尾倒数 7 个字符来查找结束索引。
js
console.log(str.slice(11, -7)); // " is u"
这些参数从末尾倒数 5 个字符来查找起始索引,并从末尾倒数 1 个字符来查找结束索引。
js
console.log(str.slice(-5, -1)); // "n us"
规范
| 规范 |
|---|
| ECMAScript® 2026 语言规范 # sec-string.prototype.slice |
浏览器兼容性
加载中…