substr() 會從指定位置開始擷取指定長度的字元,並傳回新的字串。若 start 為負數,會從字串結尾開始計算。
string.substr(start, length)
const str = 'Apples are round, and apples are juicy.';
console.log(str.substr(1, 2));
console.log(str.substr(-2, 2));
console.log(str.substr(1));
console.log(str.substr(20, 2));
輸出依序為「pp」、「Ap」、「pples are round, and apples are juicy.」與「d」。需要注意的是,substr 已較少用於新專案,slice 或 substring 通常更推薦。