本文整理了一系列實用的 JavaScript 字串擴充方法,從最常見的去除空白 trim() 開始,一路涵蓋數字提取、中文提取、位元組長度計算、格式化等,全部透過 prototype 掛到內建物件上,讓它們像 C# 一樣可以「物件.方法()」直接呼叫。
透過為 String 擴充 ResetBlank 方法,就能把連續空白壓縮成單一空白:
<script type="text/javascript">
// 合併多個空白為一個空白
String.prototype.ResetBlank = function () {
var regEx = /\s+/g;
return this.replace(regEx, ' ');
};
window.onload = function () {
var str = "你 在他想還好嗎?";
alert(str);
str = str.ResetBlank(); // 這樣就能夠調用了,跟 C# 的很像吧!
alert(str);
};
</script>
以下把常用方法一次備齊,涵蓋去除空白、提取數字與中文、位元組長度、副檔名擷取、字串格式化,以及數字補零、陣列排序、日期格式化與差值計算等:
// 清除兩邊的空格
String.prototype.trim = function () {
return this.replace(/(^\s*)|(\s*$)/g, '');
};
// 合併多個空白為一個空白
String.prototype.ResetBlank = function () {
var regEx = /\s+/g;
return this.replace(regEx, ' ');
};
// 保留數字
String.prototype.GetNum = function () {
var regEx = /[^\d]/g;
return this.replace(regEx, '');
};
// 保留中文
String.prototype.GetCN = function () {
var regEx = /[^一-龥額-齯]/g;
return this.replace(regEx, '');
};
// String 轉化為 Number
String.prototype.ToInt = function () {
return isNaN(parseInt(this)) ? this.toString() : parseInt(this);
};
// 得到字節長度
String.prototype.GetLen = function () {
var regEx = /^[一-龥額-齯]+$/;
if (regEx.test(this)) {
return this.length * 2;
} else {
var oMatches = this.match(/[x00-xff]/g);
var oLength = this.length * 2 - oMatches.length;
return oLength;
}
};
// 獲取文件全名
String.prototype.GetFileName = function () {
var regEx = /^.*/([^/?]*).*$/;
return this.replace(regEx, '$1');
};
// 獲取文件擴展名
String.prototype.GetExtensionName = function () {
var regEx = /^.*/[^/]*(.[^.?]*).*$/;
return this.replace(regEx, '$1');
};
// 替換所有
String.prototype.replaceAll = function (reallyDo, replaceWith, ignoreCase) {
if (!RegExp.prototype.isPrototypeOf(reallyDo)) {
return this.replace(new RegExp(reallyDo, (ignoreCase ? "gi" : "g")), replaceWith);
} else {
return this.replace(reallyDo, replaceWith);
}
};
// 格式化字符串
String.Format = function () {
if (arguments.length == 0) { return ''; }
if (arguments.length == 1) { return arguments[0]; }
var reg = /{(\d+)?}/g;
var args = arguments;
var result = arguments[0].replace(reg, function ($0, $1) {
return args[parseInt($1) + 1];
});
return result;
};
// 數字補零
Number.prototype.LenWithZero = function (oCount) {
var strText = this.toString();
while (strText.length < oCount) {
strText = '0' + strText;
}
return strText;
};
// Unicode 還原
Number.prototype.ChrW = function () {
return String.fromCharCode(this);
};
// 數字數組由小到大排序
Array.prototype.Min2Max = function () {
var oValue;
for (var i = 0; i < this.length; i++) {
for (var j = 0; j <= i; j++) {
if (this[i] < this[j]) {
oValue = this[i]; this[i] = this[j]; this[j] = oValue;
}
}
}
return this;
};
// 數字數組由大到小排序
Array.prototype.Max2Min = function () {
var oValue;
for (var i = 0; i < this.length; i++) {
for (var j = 0; j <= i; j++) {
if (this[i] > this[j]) {
oValue = this[i]; this[i] = this[j]; this[j] = oValue;
}
}
}
return this;
};
// 獲得數字數組中最大項
Array.prototype.GetMax = function () {
var oValue = 0;
for (var i = 0; i < this.length; i++) {
if (this[i] > oValue) { oValue = this[i]; }
}
return oValue;
};
// 獲得數字數組中最小項
Array.prototype.GetMin = function () {
var oValue = 0;
for (var i = 0; i < this.length; i++) {
if (this[i] < oValue) { oValue = this[i]; }
}
return oValue;
};
// 擴展 Date 格式化
Date.prototype.Format = function (format) {
var o = {
"M+": this.getMonth() + 1, // 月份
"d+": this.getDate(), // 日
"h+": this.getHours() % 12 == 0 ? 12 : this.getHours() % 12, // 小時
"H+": this.getHours(), // 小時
"m+": this.getMinutes(), // 分
"s+": this.getSeconds(), // 秒
"q+": Math.floor((this.getMonth() + 3) / 3), // 季度
"S": this.getMilliseconds() // 毫秒
};
var week = { "0": "日", "1": "一", "2": "二", "3": "三", "4": "四", "5": "五", "6": "六" };
if (/(y+)/.test(format)) {
format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
}
if (/(E+)/.test(format)) {
format = format.replace(RegExp.$1, ((RegExp.$1.length > 1) ? (RegExp.$1.length > 2 ? "星期" : "周") : "") + week[this.getDay() + ""]);
}
for (var k in o) {
if (new RegExp("(" + k + ")").test(format)) {
format = format.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
}
}
return format;
};
// 計算日期差值
Date.prototype.Diff = function (interval, objDate) {
if (arguments.length < 2 || objDate.constructor != Date) { return undefined; }
switch (interval) {
case 's': return parseInt((objDate - this) / 1000); // 秒差
case 'n': return parseInt((objDate - this) / 60000); // 分差
case 'h': return parseInt((objDate - this) / 3600000); // 時差
case 'd': return parseInt((objDate - this) / 86400000); // 日差
case 'w': return parseInt((objDate - this) / (86400000 * 7)); // 周差
case 'm': return (objDate.getMonth() + 1) + ((objDate.getFullYear() - this.getFullYear()) * 12) - (this.getMonth() + 1); // 月差
case 'y': return objDate.getFullYear() - this.getFullYear(); // 年差
default: return undefined;
}
};
// 檢測是否為空
Object.prototype.IsNullOrEmpty = function () {
var obj = this;
var flag = false;
if (obj == null || obj == undefined || typeof (obj) == 'undefined' || obj == '') {
flag = true;
} else if (typeof (obj) == 'string') {
obj = obj.trim();
if (obj == '') {
flag = true;
} else {
obj = obj.toUpperCase();
if (obj == 'NULL' || obj == 'UNDEFINED' || obj == '{}') {
flag = true;
}
}
} else {
flag = false;
}
return flag;
};
這一批方法幾乎涵蓋了日常字串與日期處理的常見場景。不過要提醒的是,直接擴充內建物件的 prototype 在大型專案或多人協作時,可能與其他函式庫或同事的方法命名衝突,實務上可考慮改用獨立的工具函式或 namespace 來包裝。希望這份整理對大家有所幫助。