JavaScript 字串 .length 回傳 UTF-16 代碼單元數,中文佔 1 個字元但通常視為 2 位元組。本文提供三種計算位元組長度的方法,涵蓋正則替換、逐字元判斷與現代編碼 API。
function byteLengthRegex(str) {
return str.replace(/[^\x00-\xff]/g, "aa").length;
}
// 原理:將非 ASCII 字元 (雙位元組) 替換為兩個 ASCII 字元
console.log(byteLengthRegex("中文")); // 4
console.log(byteLengthRegex("abc")); // 3
function byteLengthLoop(str) {
var bytes = 0;
for (var i = 0; i < str.length; i++) {
var c = str.charAt(i);
if (/^[\x00-\xff]$/.test(c)) { // ASCII 範圍
bytes += 1;
} else {
bytes += 2; // 視為雙位元組 (Big5/GBK 常見假設)
}
}
return bytes;
}
| 用途 | 正則 | 說明 |
|---|---|---|
| 匹配中文字元 | /[\u4e00-\u9fa5]/ | 基本漢字區 (CJK Unified Ideographs) |
| 匹配雙位元組字元 | /[^\x00-\xff]/ | 含中日韓、全形符號、Emoji 等 |
| 匹配 ASCII | /^[\x00-\xff]$/ | 0-255 字碼 |
// 瀏覽器原生,精確計算 UTF-8 位元組長度
function byteLengthUTF8(str) {
return new TextEncoder().encode(str).length;
}
console.log(byteLengthUTF8("中文")); // 6 (UTF-8 中文佔 3 位元組)
console.log(byteLengthUTF8("abc")); // 3
console.log(byteLengthUTF8("😀")); // 4 (Emoji 4 位元組)
TextEncoder 回傳 Uint8Array,.length 即精確位元組數Buffer.byteLength(str, 'utf8')// 字元 → Unicode 碼位
'中'.charCodeAt(0); // 20013 (0x4E2D)
'中'.codePointAt(0); // 20013 (支援補充平面)
// Unicode 碼位 → 字元
String.fromCharCode(20013); // "中" (BMP)
String.fromCodePoint(0x1F600); // "😀" (補充平面)
bytes += 2)TextEncoder 計算 UTF-8 位元組長度