整理實戰高頻的工具函數,按功能分模組:陣列、Cookie、URL、正則、字串、加密、日期。每個函數單一職責、無副作用、易測試,可直接複製到專案或打包成 npm 套件。
var Arr = {
indexOf: function(arr, val) { return arr.indexOf ? arr.indexOf(val) : (function(){ for(var i=arr.length;i--;) if(arr[i]===val) return i; return -1; })(); },
unique: function(arr) { var res=[]; for(var i=0;i
var Cookie = {
enabled: navigator.cookieEnabled,
set: function(name, value, days, path, domain, secure) {
var exp = days ? ';expires=' + new Date(Date.now()+days*864e5).toUTCString() : '';
document.cookie = name + '=' + encodeURIComponent(value) + exp + ';path=' + (path||'/') + (domain?';domain='+domain:'') + (secure?';secure':'');
},
get: function(name) {
var m = document.cookie.match(new RegExp('(^| )' + name + '(?:=([^;]*))?(;|$)'));
return m ? decodeURIComponent(m[2]||'') : '';
},
del: function(name, path, domain) { this.set(name, '', -1, path, domain); }
};
var Url = {
getParam: function(name, url) {
url = url || location.href;
var m = url.match(new RegExp('[?&]' + name + '=([^]*)'));
return m ? decodeURIComponent(m[1]) : null;
},
setParam: function(url, name, value) {
var re = new RegExp('([?&])' + name + '=([^]*)');
if (url.match(re)) return url.replace(re, '$1' + name + '=' + encodeURIComponent(value));
return url + (url.indexOf('?')===-1?'?':'&') + name + '=' + encodeURIComponent(value);
},
parse: function(url) {
var a = document.createElement('a'); a.href = url;
return { protocol:a.protocol, host:a.host, hostname:a.hostname, port:a.port, pathname:a.pathname, search:a.search, hash:a.hash };
}
};
var Regx = {
email: /^[\w.+-]+@[\w-]+\.[\w.-]+$/,
phoneTW: /^09\d{8}$/,
idCardTW: /^[A-Z][12]\d{8}$/,
url: /^https?:\/\/[\w.-]+\.[a-z]{2,}(\/\S*)?$/i,
ipv4: /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,
chinese: /^[\u4e00-\u9fa5]+$/,
alphanum: /^[a-zA-Z0-9]+$/
};
var Str = {
trim: function(s) { return (s||'').replace(/^\s+|\s+$/g, ''); },
truncate: function(s, len, suffix) { s = s||''; return s.length>len ? s.slice(0,len)+(suffix||'...') : s; },
capitalize: function(s) { return (s||'').charAt(0).toUpperCase() + s.slice(1).toLowerCase(); },
camelCase: function(s) { return (s||'').replace(/[-_\s]+(.)?/g, function(_,c){ return c?c.toUpperCase():''; }); },
escapeHtml: function(s) { return (s||'').replace(/&/g,'&').replace(//g,'>').replace(/"/g,'"').replace(/'/g,'''); }
};
var Crypto = {
md5: function(s) { /* 引入 md5.min.js 或使用 SubtleCrypto */ },
sha256: async function(s) { var buf=await crypto.subtle.digest('SHA-256', new TextEncoder().encode(s)); return Array.from(new Uint8Array(buf)).map(b=>b.toString(16).padStart(2,'0')).join(''); },
base64Encode: function(s) { return btoa(unescape(encodeURIComponent(s))); },
base64Decode: function(s) { return decodeURIComponent(escape(atob(s))); }
};
var DateUtil = {
format: function(d, fmt) { // fmt: 'YYYY-MM-DD HH:mm:ss'
var o = { 'M+':d.getMonth()+1, 'D+':d.getDate(), 'H+':d.getHours(), 'm+':d.getMinutes(), 's+':d.getSeconds(), 'q+':Math.floor((d.getMonth()+3)/3), 'S':d.getMilliseconds() };
if (/(Y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (d.getFullYear()+'').substr(4-RegExp.$1.length));
for (var k in o) if (new RegExp('('+k+')').test(fmt)) fmt = fmt.replace(RegExp.$1, (o[k]<'10'?'0':'')+o[k]);
return fmt;
},
addDays: function(d, days) { var nd=new Date(d); nd.setDate(nd.getDate()+days); return nd; },
diffDays: function(d1, d2) { return Math.floor((d2-d1)/864e5); },
startOfDay: function(d) { var nd=new Date(d); nd.setHours(0,0,0,0); return nd; }
};
// utils/array.js export const Arr = { ... }
// utils/cookie.js export const Cookie = { ... }
// main.js
import { Arr } from './utils/array.js';
import { Cookie } from './utils/cookie.js';
// 打包時可 Tree-shaking 僅引用需用函數