DIV CSS 佈局教程網

JavaScript substr() 方法使用詳解
編輯:JavaScript綜合知識     

方法用途

substr() 會從指定位置開始擷取指定長度的字元,並傳回新的字串。若 start 為負數,會從字串結尾開始計算。

語法

string.substr(start, length)
  • 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 通常更推薦。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved