slice() 擷取字串片段並回傳新字串,支援負索引(從末尾計算),行為直觀且一致,是現代開發首選的子字串方法。
str.slice(beginSlice[, endSlice])
<script>
const str = 'Apples are round, and apples are juicy.';
console.log(str.slice(3, -2)); // "les are round, and apples are juic"
console.log(str.slice(7)); // "are round, and apples are juicy."
console.log(str.slice(-6)); // "juicy."
console.log(str.slice(0, 6)); // "Apples"
console.log(str.slice(-12, -6)); // "juicy"
</script>
字串: A p p l e s ...
索引: 0 1 2 3 4 5 ...
負索: -22 -21 -20 -19 -18 -17 ...
| 方法 | 負索引支援 | 參數意義 | 建議度 |
|---|---|---|---|
slice() | ✅ 完整支援 | 開始、結束(不含) | ⭐⭐⭐ 推薦 |
substring() | ❌ 負值視為 0 | 開始、結束(不含) | ⭐⭐ 可用 |
substr() | ⚠︃ 僅開始支援 | 開始、長度 | ⭐ 避免使用 (legacy) |
// 移除首尾空白 (polyfill trim)
const trim = s => s.slice(s.search(/\S/), s.search(/\S\s*$/) + 1);
// 取得副檔名
const ext = filename => filename.slice(filename.lastIndexOf('.') + 1);
// 截斷並加省略號
const truncate = (s, len) => s.length > len ? s.slice(0, len) + '…' : s;
slice() 行為最符合直覺、支援負索引、無歷史包袱,應作為預設子字串擷取方法。避免使用已棄用的 substr()。