萬盛學電腦網

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

JavaScript 字元長度計算:中文雙位元、英文單位元的實用函式

需求背景

表單驗證、資料庫欄位長度限制、簡訊字數計費等場景,常需按「中文 2 個字元、英文/數字/符號 1 個字元」計算長度。

核心實作

/**
 * 計算字串視覺長度(中文=2, ASCII=1)
 * @param {string} str
 * @returns {number}
 */
function getVisualLength(str) {
  let len = 0;
  for (let i = 0; i < str.length; i++) {
    const ch = str.charCodeAt(i);
    // 基本多文種平面 BMP 範圍:中日韓統一表意文字 U+4E00 ~ U+9FFF
    // 擴展區另行處理,這裡採常見範圍
    if (ch >= 0x4e00 && ch <= 0x9fff) {
      len += 2;
    } else {
      len += 1;
    }
  }
  return len;
}

// 測試
console.log(getVisualLength("Hello世界")); // 5 + 2*2 = 9
console.log(getVisualLength("😀"));        // Emoji 在 BMP 外,算 1(實際佔 2 碼位,視需求調整)

正則替代寫法(較慢但簡潔)

function getVisualLengthRegex(str) {
  const cjk = str.match(/[\u4e00-\u9fff]/g) || [];
  return str.length + cjk.length; // 基礎長度 + 中文額外 +1(因預設算 1,需補 1 變 2)
}

進階:完整 Unicode 支援(含 Emoji、擴展漢字)

ES2015+ 可用 Array.from 或展開運算子正確處理代理對:

function getVisualLengthUnicode(str) {
  return [...str].reduce((len, ch) => {
    const code = ch.codePointAt(0);
    // 簡易判斷:CJK 統一表意文字 + 擴展 A/B + 兼容表意文字
    const isWide =
      (code >= 0x4e00 && code <= 0x9fff) ||     // CJK Unified
      (code >= 0x3400 && code <= 0x4dbf) ||     // CJK Ext-A
      (code >= 0x20000 && code <= 0x2ffff) ||   // CJK Ext-B~F (平面 2)
      (code >= 0xf900 && code <= 0xfaff) ||     // CJK Compatibility
      (code >= 0x2f800 && code <= 0x2fa1f);     // CJK Comp. Supplement
    // 全形符號、表情符號通常視為 2 寬
    const isFullwidth = code >= 0xff01 && code <= 0xff5e; // 全形標點
    const isEmoji = code >= 0x1f300 && code <= 0x1faff;   // 簡易 Emoji 範圍
    return len + (isWide || isFullwidth || isEmoji ? 2 : 1);
  }, 0);
}

應用場景範例

表單即時字數提示

<textarea id="content" maxlength="200"></textarea>
<span id="counter">0/200</span>

<script>
const $ta = $("#content");
const $counter = $("#counter");
$ta.on("input", function () {
  const len = getVisualLength(this.value);
  $counter.text(`${len}/200`);
  $counter.toggleClass("over", len > 200);
});
</script>

後端驗證一致性

前後端需**統一演算法**。資料庫若用 `VARCHAR(200)` 以 byte 計,須確認編碼(UTF-8 中文 3 bytes),不可直接套用視覺長度。建議:

  • 前端顯示「視覺長度」給使用者參考
  • 後端以 **byte 長度** 或 **字元數** 為準驗證
  • 文件明確定義計算規則

總結

基本版透過 `charCodeAt` 判斷 BMP 範圍即可覆蓋 95% 中文場景;完整版需處理代理對、擴展區、全形符號、Emoji。選擇適合專案需求的版本,並確保前後端定義一致。

copyright © 萬盛學電腦網 all rights reserved