substring() 回傳兩索引間的子字串(不含結束索引)。與 slice() 相似,但不支援負索引(負值視為 0),且自動交換較大/較小索引。
str.substring(indexStart[, indexEnd])
indexStart > indexEnd,內部自動交換(slice() 會回傳空字串)。indexEnd 省略 = 截取到結尾。<script>
const str = 'Apples are round, and apples are juicy.';
console.log(str.substring(1, 2)); // "p"
console.log(str.substring(0, 10)); // "Apples are"
console.log(str.substring(5)); // "s are round, and apples are juicy."
// 自動交換
console.log(str.substring(10, 0)); // "Apples are" (同 0,10)
// 負值處理
console.log(str.substring(-3, 5)); // "Apple" (-3→0)
console.log(str.substring(5, -3)); // "Apple" (5,0 交換後 0,5)
</script>
| 需求 | 推薦方法 | 理由 |
|---|---|---|
| 一般子字串擷取 | slice() | 支援負索引、行為一致、標準 |
| 需自動處理索引順序 | substring() | 內建交換邏輯 |
| 舊代碼維護 | substr() | 僅限相容,勿新增 |
substring() 是早期標準方法,自動交換索引特性在某些舊邏輯中被利用。現代開發請優先使用 slice(),語意更清晰且支援負索引。