String.prototype.slice()

Baseline 已廣泛支援

此特性已相當成熟,可在許多裝置和瀏覽器版本上使用。自 ⁨2015 年 7 月⁩以來,各瀏覽器均已提供此特性。

slice() 方法用於 String 物件,可提取字串的某個部分,並作為新的字串返回,會修改原字串

試一試

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) 會提取從第五個字元到第八個字元(索引為 4567 的字元)。

              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

瀏覽器相容性

另見