專案裡反覆出現的字串與陣列操作,適合沉澱為原型擴展方法,讓呼叫端保持簡潔。以下按型別整理一組實用擴充,並附上說明。
String.prototype.trim = function () {
return this.replace(/^\s+|\s+$/g, "");
};
String.prototype.ltrim = function () {
return this.replace(/^\s+/g, "");
};
String.prototype.rtrim = function () {
return this.replace(/\s+$/g, "");
};
// 分割後逐項去除空白
String.prototype.splitAndTrim = function ($delimiter, $limit) {
var $ss = this.split($delimiter, $limit);
for (var $i = 0; $i < $ss.length; $i++) $ss[$i] = $ss[$i].trim();
return $ss;
};
String.prototype.htmlEntities = function () {
return this.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>');
};
String.prototype.stripTags = function () {
return this.replace(/<([^>]+)>/g, '');
};
String.prototype.toArray = function () {
return this.split('');
};
String.prototype.toIntArray = function () {
var returnArray = [];
for (var i = 0; i < this.length; i++) {
returnArray.push(this.charCodeAt(i));
}
return returnArray;
};
String.prototype.replaceAll = function ($old, $snew) {
return this.replace(new RegExp($old, "gm"), $snew);
};
變數替換(佔位符格式化):
String.prototype.format = function () {
var args = arguments;
return this.replace(/\{(\d+)\}/g, function (m, i) {
return args[i];
});
};
var a = "I Love {0}, and You Love {1}. Where are {0}!";
a.format("You", "Me");
// 在末尾追加
String.prototype.append = function ($str) {
return this.concat($str);
};
// 刪除指定索引處的字符,索引無效則原樣返回
String.prototype.deleteCharAt = function ($sIndex) {
if ($sIndex < 0 || $sIndex >= this.length) {
return this.valueOf();
} else if ($sIndex == 0) {
return this.substring(1, this.length);
} else if ($sIndex == this.length - 1) {
return this.substring(0, this.length - 1);
} else {
return this.substring(0, $sIndex) + this.substring($sIndex + 1);
}
};
// 刪除兩個索引之間的內容(索引所在字符不刪除),依賴 deleteCharAt
String.prototype.deleteString = function ($sIndex, $eIndex) {
if ($sIndex == $eIndex) {
return this.deleteCharAt($sIndex);
}
if ($sIndex > $eIndex) {
var tIndex = $eIndex;
$eIndex = $sIndex;
$sIndex = tIndex;
}
if ($sIndex < 0) $sIndex = 0;
if ($eIndex > this.length - 1) $eIndex = this.length - 1;
return this.substring(0, $sIndex + 1) + this.substring($eIndex, this.length);
};
// 在指定位置之後插入
String.prototype.insert = function ($ofset, $str) {
if ($ofset < 0 || $ofset >= this.length - 1) {
return this.concat($str);
}
return this.substring(0, $ofset) + $str + this.substring($ofset + 1);
};
// 將指定位置的字符替換為另一段內容
String.prototype.setCharAt = function ($ofset, $str) {
if ($ofset < 0 || $ofset >= this.length - 1) {
return this.valueOf();
}
return this.substring(0, $ofset) + $str + this.substring($ofset + 1);
};
// 替換從 start 起、長度 len 的片段
String.prototype.replaceLen = function (start, len, replaced) {
if (!len) return this;
if (start >= this.length) return this;
var returnSeg = '', returnSeg2 = '';
for (var i = 0; i < this.length; i++) {
var c = this.charAt(i);
if (i < start) returnSeg += c;
if (i >= start + len) returnSeg2 += c;
}
return returnSeg + replaced + returnSeg2;
};
這個方法在模板填充場景特別好用,例如把「***天***小時」替換成「<input />天<input />小時」:
String.prototype.replaceChar = function (target, replaced, start) {
if (!target) return this;
if (!start) start = 0;
var returnVal = this.substring(0, start);
var index = 0;
for (var i = start; i < this.length; i++) {
var c = this.charAt(i);
target = typeof target == 'function' ? target.call(this, index) : target;
if (c == target) {
returnVal += typeof replaced == 'function' ? replaced.call(this, index) : replaced;
// 連續相同字符視為一次匹配
while (i < this.length - 1 && this.charAt(i + 1) == c) {
i++;
}
index++;
} else {
returnVal += c;
}
}
return returnVal;
};
// 反序排列
String.prototype.reverse = function () {
var str = "";
for (var i = this.length - 1; i >= 0; i--) {
str = str.concat(this.charAt(i));
}
return str;
};
// 是否以某字串開頭 / 結尾
String.prototype.startsWith = function (str) {
return this.substr(0, str.length) == str;
};
String.prototype.endsWith = function ($str) {
return this.substr(this.length - $str.length) == $str;
};
// 忽略大小寫比較
String.prototype.equalsIgnoreCase = function ($str) {
if (this.length != $str.length) {
return false;
}
return this.toLowerCase() == $str.toLowerCase();
};
// 是否包含某子字串
String.prototype.contains = function ($str) {
return this.indexOf($str) > -1 ? true : false;
};
// 計算顯示長度:漢字占 2,英文字符占 1
String.prototype.ucLength = function () {
var len = 0;
for (var i = 0; i < this.length; i++) {
if (this.charCodeAt(i) > 255) len += 2;
else len++;
}
return len;
};
// 左側填充
String.prototype.lpad = function (len, s) {
var a = new Array(this);
var n = (len - this.length);
for (var i = 0; i < n; i++) {
a.unshift(s);
}
return a.join("");
};
// 右側填充
String.prototype.rpad = function (len, s) {
var a = new Array(this);
var n = (len - this.length);
for (var i = 0; i < n; i++) {
a.push(s);
}
return a.join("");
};
// 首字母大寫
String.prototype.ucwords = function () {
return this.substring(0, 1).toUpperCase().concat(this.substring(1));
};
// 將 2008-04-02 10:08:44 形式的字串轉為日期物件
String.prototype.toDate = function () {
var str = this.replace(/-/g, "/");
return new Date(str);
};
// 轉為指定精度的浮點數
String.prototype.toFloat = function (precision) {
precision = precision || 2;
return parseFloat(this, 10).toFixed(precision);
};
// 轉為整數
String.prototype.toInt = function () {
return parseInt(this, 10).toString();
};
// 與加數相加後以字串返回
String.prototype.add = function (addend) {
var sum = parseFloat(this, 10) + parseFloat(addend, 10);
return sum + "";
};
// 十進制轉其他進制(nextScale 如 2、8、16)
String.prototype.shiftScale = function (nextScale) {
return parseFloat(this).toString(nextScale);
};
// 任意進制互轉
String.prototype.scaleShift = function (preScale, nextScale) {
return parseInt(this, preScale).toString(nextScale);
};
String.prototype.dbc2sbc = function () {
return this.replace(/[\uff01-\uff5e]/g, function (a) {
return String.fromCharCode(a.charCodeAt(0) - 65248);
}).replace(/\u3000/g, " ");
};
在尚未原生支援 every、filter、forEach、map、some 的環境中,可以先做能力檢測再補上:
var isNumeric = function (x) {
// x 為數字時回傳 truthy,否則回傳 falsy
var RegExp = /^(-)?(\d*)(\.?)?(\d*)$/;
return String(x).match(RegExp);
};
var myArray = [1, 'two', 3, 'four', 5, 'six', 7, 'eight', 9, 'ten'];
myArray.filter(isNumeric); // 1, 3, 5, 7, 9
myArray.some(isNumeric); // true
myArray.every(isNumeric); // false
var printArray = function (x, idx) {
document.writeln('[' + idx + '] = ' + x);
};
myArray.forEach(printArray);
if (!Array.prototype.every) {
Array.prototype.every = function (fun /*, thisp */) {
var len = this.length;
if (typeof fun != "function") throw new TypeError();
var thisp = arguments[1];
for (var i = 0; i < len; i++) {
if (i in this && !fun.call(thisp, this[i], i, this)) return false;
}
return true;
};
}
if (!Array.prototype.filter) {
Array.prototype.filter = function (fun /*, thisp */) {
var len = this.length;
if (typeof fun != "function") throw new TypeError();
var res = new Array();
var thisp = arguments[1];
for (var i = 0; i < len; i++) {
if (i in this) {
var val = this[i]; // 防止 fun 修改 this 導致取值異常
if (fun.call(thisp, val, i, this)) res.push(val);
}
}
return res;
};
}
if (!Array.prototype.forEach) {
Array.prototype.forEach = function (fun /*, thisp */) {
var len = this.length;
if (typeof fun != "function") throw new TypeError();
var thisp = arguments[1];
for (var i = 0; i < len; i++) {
if (i in this) fun.call(thisp, this[i], i, this);
}
};
}
if (!Array.prototype.map) {
Array.prototype.map = function (fun /*, thisp */) {
var len = this.length;
if (typeof fun != "function") throw new TypeError();
var res = new Array(len);
var thisp = arguments[1];
for (var i = 0; i < len; i++) {
if (i in this) res[i] = fun.call(thisp, this[i], i, this);
}
return res;
};
}
if (!Array.prototype.some) {
Array.prototype.some = function (fun /*, thisp */) {
var len = this.length;
if (typeof fun != "function") throw new TypeError();
var thisp = arguments[1];
for (var i = 0; i < len; i++) {
if (i in this && fun.call(thisp, this[i], i, this)) return true;
}
return false;
};
}
// 數值排序(預設的 sort 是字典序,需自訂比較器)
Array.prototype.sortNum = function () {
return this.sort(function (a, b) { return a - b; });
};
// 查找所有符合條件的索引;找不到回傳 false
Array.prototype.find = function (searchStr) {
var returnArray = false;
for (var i = 0; i < this.length; i++) {
if (typeof (searchStr) == 'function') {
if (searchStr.test(this[i])) {
if (!returnArray) returnArray = [];
returnArray.push(i);
}
} else {
if (this[i] === searchStr) {
if (!returnArray) returnArray = [];
returnArray.push(i);
}
}
}
return returnArray;
};
// 隨機打亂順序
Array.prototype.shuffle = function () {
for (var rnd, tmp, i = this.length; i; rnd = parseInt(Math.random() * i),
tmp = this[--i], this[i] = this[rnd], this[rnd] = tmp);
return this;
};
// 逐項比較兩個陣列是否相同
Array.prototype.compare = function (testArr) {
if (this.length != testArr.length) return false;
for (var i = 0; i < testArr.length; i++) {
if (this[i].compare) {
if (!this[i].compare(testArr[i])) return false;
}
if (this[i] !== testArr[i]) return false;
}
return true;
};
// 最大值與最小值
Array.prototype.max = function () {
return Math.max.apply({}, this);
};
Array.prototype.min = function () {
return Math.min.apply({}, this);
};
// 去掉重複值(利用物件可當雜湊表使用的特性)
Array.prototype.unique = function () {
var data = this || [];
var a = {};
for (var i = 0; i < data.length; i++) {
a[data[i]] = true; // 以值作為鍵,天然去重
}
data.length = 0;
for (var i in a) {
this[data.length] = i;
}
return data;
};
Array.prototype.addAll = function ($array) {
if ($array == null || $array.length == 0) return;
for (var $i = 0; $i < $array.length; $i++) this.push($array[$i]);
};
Array.prototype.contains = function ($value) {
for (var $i = 0; $i < this.length; $i++) {
if (this[$i] == $value) return true;
}
return false;
};
Array.prototype.indexOf = function ($value) {
for (var $i = 0; $i < this.length; $i++) {
if (this[$i] == $value) return $i;
}
return -1;
};
if (!Array.prototype.lastIndexOf) {
Array.prototype.lastIndexOf = function (elt /*, from */) {
var len = this.length;
var from = Number(arguments[1]);
if (isNaN(from)) {
from = len - 1;
} else {
from = (from < 0) ? Math.ceil(from) : Math.floor(from);
if (from < 0) from += len;
else if (from >= len) from = len - 1;
}
for (; from > -1; from--) {
if (from in this && this[from] === elt) return from;
}
return -1;
};
}
Array.prototype.insertAt = function ($value, $index) {
if ($index < 0) this.unshift($value);
else if ($index >= this.length) this.push($value);
else this.splice($index, 0, $value);
};
// 依索引刪除
Array.prototype.removeByIndex = function ($n) {
if ($n < 0) {
return this; // 索引無效則不動
}
return this.slice(0, $n).concat(this.slice($n + 1, this.length));
};
// 依值刪除(依賴 indexOf)
Array.prototype.remove = function ($value) {
var $index = this.indexOf($value);
if ($index != -1) this.splice($index, 1);
};
Array.prototype.removeAll = function () {
while (this.length > 0) this.pop();
};
Array.prototype.replace = function ($oldValue, $newValue) {
for (var $i = 0; $i < this.length; $i++) {
if (this[$i] == $oldValue) {
this[$i] = $newValue;
return;
}
}
};
Array.prototype.swap = function ($a, $b) {
if ($a == $b) return;
var $tmp = this[$a];
this[$a] = this[$b];
this[$b] = $tmp;
};
以下是一組以 splice 為基礎、對 push、pop、shift、unshift、slice、join、reverse 等方法的示範性實作,主要價值在於理解這些方法的內部行為:
// 自 splice 起,刪除 delLen 個元素並可插入一項
Array.prototype.splice = function (start, delLen, item) {
var len = this.length;
start = start < 0 ? 0 : start > len ? len : start ? start : 0;
delLen = delLen < 0 ? 0 : delLen > len ? len : delLen ? delLen : len;
var arr = [], res = [];
var iarr = 0, ires = 0, i = 0;
for (i = 0; i < len; i++) {
if (i < start || ires >= delLen) {
arr[iarr++] = this[i];
} else {
res[ires++] = this[i];
if (item && ires == delLen) {
arr[iarr++] = item;
}
}
}
if (item && ires < delLen) arr[iarr] = item;
for (var j = 0; j < arr.length; j++) {
this[j] = arr[j];
}
this.length = arr.length;
return res;
};
Array.prototype.pop = function () {
return this.splice(this.length - 1, 1)[0];
};
Array.prototype.shift = function () {
if (!this) return [];
return this.splice(0, 1)[0];
};
Array.prototype.push = function () {
Array.prototype.splice.apply(this,
[this.length, 0].concat(Array.prototype.slice.apply(arguments)));
return this.length;
};
Array.prototype.unshift = function () {
Array.prototype.splice.apply(this,
[0, 0].concat(Array.prototype.slice.apply(this, arguments)));
};
Array.prototype.concat = function () {
var i = 0;
while (i < arguments.length) {
if (typeof arguments[i] === 'object'
&& typeof arguments[i].splice === 'function'
&& !arguments[i].propertyIsEnumerable('length')) {
// 逐一複製陣列元素
var j = 0;
while (j < arguments[i].length) {
this.splice(this.length, 0, arguments[i][j++]);
}
i++;
} else {
this[this.length] = arguments[i++];
}
}
return this;
};
Array.prototype.join = function (separator) {
var i = 0, str = "";
while (i < this.length) str += this[i++] + separator;
return str;
};
Array.prototype.reverse = function () {
for (var i = 0; i < this.length / 2; i++) {
var temp = this[i];
this[i] = this[this.length - 1 - i];
this[this.length - 1 - i] = temp;
}
return this;
};
Array.prototype.slice = function (start, end) {
var len = this.length;
start = start < 0 ? start += len : start ? start : 0;
end = end < 0 ? end += len : end > len ? len : end ? end : len;
var i = start, res = [];
while (i < end) {
res.push(this[i++]);
}
return res;
};
使用這類擴充時有兩點值得注意:其一,直接改寫內建原型會影響全域,若與其他程式庫或未來的語言標準衝突,排查成本很高,因此更推薦以獨立工具函數或 ES6 之後的 Object.assign/解構語法來組織;其二,上述多數方法在現代環境中已有原生且效能更好的實作,這份彙編更适合當作理解底層行為的參考,而非生產環境的首選。