substr() 從指定位置擷取指定長度的子字串。雖然廣泛支援,但屬於 Annex B (規範性附錄)、非核心標準,MDN 標記為「已棄用」,新代碼請改用 slice() 或 substring()。
str.substr(start[, length])
<script>
const str = 'Apples are round, and apples are juicy.';
console.log(str.substr(1, 2)); // "pp"
console.log(str.substr(-2, 2)); // "y." (倒數2字元取2個)
console.log(str.substr(1)); // "pples are round, and apples are juicy."
console.log(str.substr(-20, 2)); // "nd"
console.log(str.substr(20, 2)); // "d"
</script>
const s = '0123456789';
s.slice(2, 5); // "234" (索引 2 到 4)
s.substr(2, 5); // "23456" (索引 2 起長度 5)
s.slice(-3); // "789" (倒數3個)
s.substr(-3); // "789" (同)
s.slice(5, 2); // "" (開始>結束 回傳空)
s.substr(5, -2); // "" (負長度視為0)
| substr 用法 | slice 替代 |
|---|---|
str.substr(start, len) | str.slice(start, start + len) |
str.substr(-n) | str.slice(-n) |
str.substr(-n, len) | str.slice(-n, -n + len) |
substr() 為歷史產物,參數語意(長度而非結束索引)易與 slice() 混淆。新專案一律使用 slice(),既標準又直觀。