DIV CSS 佈局教程網

JS Trim 字串去空白:正則表達式實作
編輯:關於JavaScript     

需求

有時需要移除字串前後空白,例如表單輸入或資料比對。

正則表達式版本

String.prototype.Trim = function() {
  return this.replace(/^\s+/, "").replace(/\s+$/, "");
};
String.prototype.LTrim = function() {
  return this.replace(/^\s+/, "");
};
String.prototype.RTrim = function() {
  return this.replace(/\s+$/, "");
};

使用

"  hello  ".Trim(); // "hello"

建議

現代瀏覽器多已支援 String.prototype.trim,可直接使用。若需相容舊環境,再自行擴充。

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