DIV CSS 佈局教程網

JavaScript 常用字串輔助函式整理
編輯:關於JavaScript     

字串處理常需要補位、去空白、首字母大寫、反轉與前後綴判斷。以下整理可擴充 String.prototype 的常用方法。

左右補位

String.prototype.padLeft = function (padChar, width) {
  var ret = this;
  while (ret.length < width) {
    if (ret.length + padChar.length < width) {
      ret = padChar + ret;
    } else {
      ret = padChar.substring(0, width - ret.length) + ret;
    }
  }
  return ret;
};

padRight 概念相同,只是把補位字元加在右側。

去空白

String.prototype.trim = function () {
  return this.replace(/^\s+/, '').replace(/\s+$/, '');
};
String.prototype.trimLeft = function () {
  return this.replace(/^\s+/, '');
};
String.prototype.trimRight = function () {
  return this.replace(/\s+$/, '');
};

首字母大寫與反轉

String.prototype.caption = function () {
  if (this) {
    return this.charAt(0).toUpperCase() + this.substr(1);
  }
  return this;
};
String.prototype.reverse = function () {
  var ret = '';
  for (var i = this.length - 1; i >= 0; i--) {
    ret += this.charAt(i);
  }
  return ret;
};

前後綴判斷

String.prototype.startWith = function (compareValue, ignoreCase) {
  if (ignoreCase) {
    return this.toLowerCase().indexOf(compareValue.toLowerCase()) === 0;
  }
  return this.indexOf(compareValue) === 0;
};
String.prototype.endWith = function (compareValue, ignoreCase) {
  if (ignoreCase) {
    return this.toLowerCase().lastIndexOf(compareValue.toLowerCase()) === this.length - compareValue.length;
  }
  return this.lastIndexOf(compareValue) === this.length - compareValue.length;
};

這類擴充能提升字串操作效率,但正式專案中也應注意避免與原生方法衝突。

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