萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript String.prototype.slice() 完整指南:靈活擷取子字串

前言

slice() 擷取字串片段並回傳新字串,支援負索引(從末尾計算),行為直觀且一致,是現代開發首選的子字串方法。

語法

str.slice(beginSlice[, endSlice])

參數說明

  • beginSlice:起始索引(含)。負值 = length + beginSlice。
  • endSlice(可選):結束索引(不含)。負值 = length + 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 ...

與 substring()、substr() 比較

方法負索引支援參數意義建議度
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()。

copyright © 萬盛學電腦網 all rights reserved