日常開發中有一些反覆出現的小需求:截斷字串、去空格、格式化日期、操作 Cookie、跨瀏覽器綁事件。本文收集了一批實用的工具函式,並標註現代寫法。
function cutstr(str, len) {
var temp, icount = 0, patrn = /[^\x00-\xff]/, strre = "";
for (var i = 0; i < str.length; i++) {
if (icount < len - 1) {
temp = str.substr(i, 1);
if (patrn.exec(temp) == null) {
icount = icount + 1;
} else {
icount = icount + 2;
}
strre += temp;
} else {
break;
}
}
return strre + "...";
}
原理是用 /[^\x00-\xff]/ 判斷是否為非 ASCII 字元,中文算 2 個單位。現代寫法可以直接用 spread 轉陣列再 slice:
const cutstr = (s, n) => [...s].slice(0, n).join('') + '...';
String.prototype.replaceAll = function (s1, s2) {
return this.replace(new RegExp(s1, "gm"), s2);
};
ES2021 已內建 replaceAll,不必自己擴充原型。注意擴充原生 prototype 容易造成衝突,能避免就避免。
String.prototype.trim = function () {
return this.replace(/^\s*(.*?)\s*$/, "$1");
};
ES5 起 trim 已是標準方法,另有 trimStart / trimEnd 可只處理單側。
function ltrim(s) { return s.replace(/^(\s*)/, ""); }
function rtrim(s) { return s.replace(/(\s*)$/, ""); }
或者直接用 s.trimStart() 與 s.trimEnd()。
String.prototype.startWith = function (s) { return this.indexOf(s) == 0; };
String.prototype.endWith = function (s) {
var d = this.length - s.length;
return (d >= 0 && this.lastIndexOf(s) == d);
};
標準做法是 s.startsWith(x) 與 s.endsWith(x),ES6 起可直接使用,且支援第二個參數指定起算位置。
function HtmlEncode(text) {
return text.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
這段程式碼非常重要:把使用者輸入直接插入 innerHTML 會造成 XSS。轉義順序必須先處理 &,否則後續插入的 < 會被二次轉義。
更安全的做法是用 textContent 而非 innerHTML,瀏覽器會自動處理:
el.textContent = userInput; // 天然安全
Date.prototype.Format = function (formatStr) {
var str = formatStr;
var Week = ['日', '一', '二', '三', '四', '五', '六'];
str = str.replace(/yyyy|YYYY/, this.getFullYear());
str = str.replace(/yy|YY/, (this.getYear() % 100) > 9
? (this.getYear() % 100).toString() : '0' + (this.getYear() % 100));
str = str.replace(/MM/, (this.getMonth() + 1) > 9
? (this.getMonth() + 1).toString() : '0' + (this.getMonth() + 1));
str = str.replace(/M/g, this.getMonth() + 1);
str = str.replace(/w|W/g, Week[this.getDay()]);
str = str.replace(/dd|DD/, this.getDate() > 9
? this.getDate().toString() : '0' + this.getDate());
str = str.replace(/d|D/g, this.getDate());
str = str.replace(/hh|HH/, this.getHours() > 9
? this.getHours().toString() : '0' + this.getHours());
str = str.replace(/h|H/g, this.getHours());
str = str.replace(/mm/, this.getMinutes() > 9
? this.getMinutes().toString() : '0' + this.getMinutes());
str = str.replace(/m/g, this.getMinutes());
str = str.replace(/ss|SS/, this.getSeconds() > 9
? this.getSeconds().toString() : '0' + this.getSeconds());
str = str.replace(/s|S/g, this.getSeconds());
return str;
};
現代寫法用 Intl.DateTimeFormat,內建多語言與各地區格式:
new Intl.DateTimeFormat('zh-TW', {
year: 'numeric', month: '2-digit', day: '2-digit',
hour: '2-digit', minute: '2-digit'
}).format(new Date());
// 或用 toLocaleString('zh-TW') 取得預設格式
function isDigit(value) {
return /^[0-9]*$/.test(value) && value !== "";
}
若含小數或負號,改用 /^-?\d+(\.\d+)?$/,或直接用 Number.isFinite(Number(v))。
function setCookie(name, value, hours) {
var d = new Date();
var offset = 8; // UTC+8
var utc = d.getTime() + (d.getTimezoneOffset() * 60000);
var nd = utc + (3600000 * offset);
var exp = new Date(nd);
exp.setTime(exp.getTime() + hours * 60 * 60 * 1000);
document.cookie = name + "=" + encodeURIComponent(value)
+ ";path=/;expires=" + exp.toUTCString();
}
那幾行時區換算是多餘的,Date 物件本身就會以本地時區運作,直接寫 new Date(Date.now() + hours * 3600000) 即可。另外請用 encodeURIComponent 而非已被棄用的 escape。
function getCookie(name) {
var arr = document.cookie.match(new RegExp("(^| )" + name + "=([^;]*)(;|$)"));
if (arr != null) return decodeURIComponent(arr[2]);
return null;
}
function AddFavorite(sURL, sTitle) {
try {
window.external.addFavorite(sURL, sTitle);
} catch (e) {
try {
window.sidebar.addPanel(sTitle, sURL, "");
} catch (e) {
alert("加入收藏失敗,請使用 Ctrl+D 進行添加");
}
}
}
這類功能基於安全理由已被現代瀏覽器全面移除,程式碼保留僅供參考。設為首頁同理,已不可能實現。
function LoadStyle(url) {
try {
document.createStyleSheet(url); // 舊 IE
} catch (e) {
var cssLink = document.createElement('link');
cssLink.rel = 'stylesheet';
cssLink.type = 'text/css';
cssLink.href = url;
document.getElementsByTagName('head')[0].appendChild(cssLink);
}
}
function addEventSamp(obj, evt, fn) {
if (!obj) return;
if (obj.addEventListener) {
obj.addEventListener(evt, fn, false);
} else if (obj.attachEvent) {
obj.attachEvent('on' + evt, fn);
} else {
obj['on' + evt] = fn;
}
}
移除事件的邏輯相同,只是把 addEventListener 換成 removeEventListener、attachEvent 換成 detachEvent。注意移除時傳入的函式參照必須與綁定時相同,否則移不掉——這也是為什麼不能用匿名函式做需要後續移除的監聽器。
如今只需支援現代瀏覽器時,直接用 el.addEventListener 即可,上面那層判斷都可以省下。
function $(id) {
return !id ? null : document.getElementById(id);
}
現代寫法是 document.getElementById(id),或用 document.querySelector('#' + id) 統一用選擇器語法。
上面好幾個範例都直接在 String.prototype 上掛方法。這在早期很常見,但現在被視為不良實踐:一旦兩個函式庫擴充了同名方法,就會互相覆蓋,而且會讓 for...in 的行為變得難以預期。把工具函式放在獨立物件或模組中導出,是更安全的組織方式。