純原生 JS 實現,零依賴、高性能、易樹搖。本文精選前 15 個高頻工具函數,涵蓋字符串截取、域名解析、空格清理、HTML 轉義、日期格式化、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);
icount += patrn.test(temp) ? 2 : 1; // 中文算 2 字節
strre += temp;
} else break;
}
return strre + "...";
}
function getHost(url) {
url = url || window.location.href;
var match = url.match(/^\w+:\/\/([^/]+)/);
return match ? match[1] : "null";
}
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g, '');
};
String.prototype.replaceAll = function(s1, s2) {
return this.replace(new RegExp(s1.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'gm'), s2);
};
function HtmlEncode(text) {
return text.replace(/&/g, '&')
.replace(/"/g, '"')
.replace(//g, '>');
}
function HtmlDecode(text) {
return text.replace(/&/g, '&')
.replace(/"/g, '"')
.replace(/</g, '<')
.replace(/>/g, '>');
}
Date.prototype.Format = function(fmt) {
var o = {
"M+": this.getMonth() + 1,
"d+": this.getDate(),
"h+": this.getHours(),
"m+": this.getMinutes(),
"s+": this.getSeconds(),
"q+": Math.floor((this.getMonth() + 3) / 3),
"S": this.getMilliseconds()
};
if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
for (var k in o) if (new RegExp("(" + k + ")").test(fmt))
fmt = fmt.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
return fmt;
};
// 使用:new Date().Format("yyyy-MM-dd hh:mm:ss.S") → "2024-01-15 14:30:45.123"
function isDigit(value) {
return /^\d+$/.test(value);
}
function setCookie(name, value, hours) {
var exp = new Date();
exp.setTime(exp.getTime() + hours * 3600 * 1000);
document.cookie = name + "=" + encodeURIComponent(value) +
";expires=" + exp.toGMTString() + ";path=/;domain=yourdomain.com";
}
function getCookie(name) {
var match = document.cookie.match(new RegExp("(^| )" + name + "=([^;]*)(;|$)"));
return match ? decodeURIComponent(match[2]) : null;
}
function AddFavorite(url, title) {
try { window.external.addFavorite(url, title); }
catch(e) {
try { window.sidebar.addPanel(title, url, ""); }
catch(e) { alert("請使用 Ctrl+D 添加收藏"); }
}
}
function setHomepage(url) {
if (document.all) document.body.style.behavior = 'url(#default#homepage)';
else if (window.sidebar) {
try { netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect"); }
catch(e) { alert("瀏覽器拒絕,請手動設置"); }
}
}
if (navigator.userAgent.toLowerCase().indexOf("msie 6") > -1) {
try { document.execCommand("BackgroundImageCache", false, true); } catch(e) {}
}
function LoadStyle(url) {
var link = document.createElement('link');
link.rel = 'stylesheet'; link.href = url;
document.head.appendChild(link);
}
function evalscript(s) {
if (!/<script/i.test(s)) return s;
var scripts = s.match(/<script[^>]*>([\s\S]*?)<\/script>/gi) || [];
scripts.forEach(function(script) {
var srcMatch = script.match(/src=["']([^"']+)["']/i);
if (srcMatch) {
// 動態加載外部腳本
var s = document.createElement('script');
s.src = srcMatch[1];
document.head.appendChild(s);
} else {
// 執行內聯腳本
eval(script.replace(/<\/?script[^>]*>/gi, ''));
}
});
return s.replace(/<script[\s\S]*?<\/script>/gi, '');
}
後續 85 個函數將涵蓋:數組去重/扁平化、深拷貝、防抖節流、設備檢測、本地存儲封裝、AES 加密、Canvas 圖片壓縮、WebSocket 重連等進階主題。建議收藏備查,按需複製到項目工具庫。