字串處理常需要補位、去空白、首字母大寫、反轉與前後綴判斷。以下整理可擴充 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;
};這類擴充能提升字串操作效率,但正式專案中也應注意避免與原生方法衝突。