現代前端框架雖然強大,但純原生 JavaScript 技巧在輕量專案、效能敏感場景或面試中依然不可或缺。本文精選 10 個高頻使用的原生工具函數,涵蓋字串、日期、Cookie、驗證等領域,皆經實戰驗證,可直接複製到專案工具庫中。
/**
* 依字節長度截斷字串,中文算 2 字節,英文算 1
* @param {string} str 原字串
* @param {number} len 最大字節長度
* @returns {string} 截斷後字串,超長自動加「...」
*/
function cutStrByByte(str, len) {
let byteCount = 0;
let result = '';
for (const ch of str) {
byteCount += /[\u0000-\u00ff]/.test(ch) ? 1 : 2;
if (byteCount > len) break;
result += ch;
}
return byteCount > len ? result + '...' : result;
}
// 測試
console.log(cutStrByByte('Hello世界', 8)); // "Hello世..."
function getHost(url = window.location.href) {
try {
return new URL(url).host; // 現代瀏覽器原生支援
} catch {
// 降級相容
const match = url.match(/^(?:https?:\/\/)?([^\/]+)/i);
return match ? match[1] : 'null';
}
}
if (!String.prototype.trim) {
String.prototype.trim = function () {
return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
};
}
String.prototype.replaceAll = function (search, replacement) {
return this.replace(new RegExp(search.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'g'), replacement);
};
// 用法
'foo bar foo'.replaceAll('foo', 'baz'); // "baz bar baz"
function htmlEncode(text) {
return String(text)
.replace(/&/g, '&')
.replace(/"/g, '"')
.replace(/'/g, ''')
.replace(//g, '>');
}
function htmlDecode(text) {
return String(text)
.replace(/&/g, '&')
.replace(/"/g, '"')
.replace(/'/g, "'")
.replace(/</g, '<')
.replace(/>/g, '>');
}
Date.prototype.format = function (fmt = 'yyyy-MM-dd HH:mm:ss') {
const opt = {
'y+': this.getFullYear(),
'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() // 毫秒
};
for (const k in opt) {
const regex = new RegExp(`(${k})`);
if (regex.test(fmt)) {
const val = String(opt[k]);
fmt = fmt.replace(regex, k.length === 1 ? val : val.padStart(RegExp.$1.length, '0'));
}
}
return fmt;
};
// 用法
console.log(new Date().format('yyyy年MM月dd日 HH:mm:ss.S'));
// 2025年06月15日 14:30:45.123
function isNumericString(val) {
return /^\d+$/.test(String(val).trim());
}
// 注意:僅判斷非負整數,浮點數、負數、科學記號需另行處理
/**
* @param {string} name
* @param {string} value
* @param {Object} [options] { days, domain, path, secure, sameSite }
*/
function setCookie(name, value, options = {}) {
const { days = 30, domain, path = '/', secure = false, sameSite = 'Lax' } = options;
const expires = new Date(Date.now() + days * 864e5).toUTCString();
let cookie = `${encodeURIComponent(name)}=${encodeURIComponent(value)};expires=${expires};path=${path}`;
if (domain) cookie += `;domain=${domain}`;
if (secure) cookie += ';secure';
cookie += `;samesite=${sameSite}`;
document.cookie = cookie;
}
function getCookie(name) {
const match = document.cookie.match(new RegExp(`(^|;\\s*)${encodeURIComponent(name)}=([^;]*)`));
return match ? decodeURIComponent(match[2]) : null;
}
| 功能 | 原生寫法 | 現代替代/補充 |
|---|---|---|
| 字串截斷 | cutStrByByte | CSS text-overflow: ellipsis(單行)、-webkit-line-clamp(多行) |
| URL 解析 | getHost | new URL(url).host、URLSearchParams |
| 日期格式化 | Date.prototype.format | Intl.DateTimeFormat、date-fns、dayjs |
| Cookie | setCookie/getCookie | js-cookie、localStorage/sessionStorage、IndexedDB |
| HTML 編碼 | htmlEncode | DOMPurify、框架內建(React dangerouslySetInnerHTML 等) |
這 10 個技巧涵蓋了日常開發 80% 以上的高頻原生需求。雖然成熟工具庫(Lodash、date-fns 等)提供更完善的方案,但理解原生實作原理有助於在無法引入依賴的環境(如廣告 SDK、微前端子應用、舊專案維護)中快速解決問題。建議將常用函數整理為專案共用的 utils/helpers.js,並加上 JSDoc 與單元測試,長期維護更無負擔。