萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

10 個實用 JavaScript 原生技巧:字串截斷、日期格式化、Cookie 操作等

現代前端框架雖然強大,但純原生 JavaScript 技巧在輕量專案、效能敏感場景或面試中依然不可或缺。本文精選 10 個高頻使用的原生工具函數,涵蓋字串、日期、Cookie、驗證等領域,皆經實戰驗證,可直接複製到專案工具庫中。

1. 字串按字節長度截斷(支援中英混排)

/**
 * 依字節長度截斷字串,中文算 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世..."

2. 從 URL 擷取主機名

function getHost(url = window.location.href) {
  try {
    return new URL(url).host; // 現代瀏覽器原生支援
  } catch {
    // 降級相容
    const match = url.match(/^(?:https?:\/\/)?([^\/]+)/i);
    return match ? match[1] : 'null';
  }
}

3. 去除首尾空白(polyfill 寫法)

if (!String.prototype.trim) {
  String.prototype.trim = function () {
    return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
  };
}

4. 全域替換所有匹配字串

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"

5. HTML 實體編碼(防 XSS 基礎)

function htmlEncode(text) {
  return String(text)
    .replace(/&/g, '&')
    .replace(/"/g, '"')
    .replace(/'/g, ''')
    .replace(//g, '>');
}

6. HTML 實體解碼

function htmlDecode(text) {
  return String(text)
    .replace(/&/g, '&')
    .replace(/"/g, '"')
    .replace(/'/g, "'")
    .replace(/</g, '<')
    .replace(/>/g, '>');
}

7. 日期格式化(支援 yyyy/MM/dd HH:mm:ss 等自訂格式)

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

8. 判斷是否為純數字字串

function isNumericString(val) {
  return /^\d+$/.test(String(val).trim());
}
// 注意:僅判斷非負整數,浮點數、負數、科學記號需另行處理

9. 設定 Cookie(支援自訂網域、路徑、SameSite)

/**
 * @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;
}

10. 讀取 Cookie

function getCookie(name) {
  const match = document.cookie.match(new RegExp(`(^|;\\s*)${encodeURIComponent(name)}=([^;]*)`));
  return match ? decodeURIComponent(match[2]) : null;
}

使用建議與現代替代方案

功能原生寫法現代替代/補充
字串截斷cutStrByByteCSS text-overflow: ellipsis(單行)、-webkit-line-clamp(多行)
URL 解析getHostnew URL(url).host、URLSearchParams
日期格式化Date.prototype.formatIntl.DateTimeFormat、date-fns、dayjs
CookiesetCookie/getCookiejs-cookie、localStorage/sessionStorage、IndexedDB
HTML 編碼htmlEncodeDOMPurify、框架內建(React dangerouslySetInnerHTML 等)

結語

這 10 個技巧涵蓋了日常開發 80% 以上的高頻原生需求。雖然成熟工具庫(Lodash、date-fns 等)提供更完善的方案,但理解原生實作原理有助於在無法引入依賴的環境(如廣告 SDK、微前端子應用、舊專案維護)中快速解決問題。建議將常用函數整理為專案共用的 utils/helpers.js,並加上 JSDoc 與單元測試,長期維護更無負擔。

copyright © 萬盛學電腦網 all rights reserved