資料庫欄位常以位元組長度限制(如 VARCHAR(200)),中文字元佔 2-4 位元組(UTF-8),JS 中 `String.length 以 UTF-16 代碼單元計數(中英皆為 1)。需自訂函式計算「視覺寬度」或「位元組長度」。
length`,BMP 字元 1,補充平面字元(Emoji、罕用字)2。function getVisualLength(str) {
// 匹配非 ASCII 可列印字元(含中文、全形符號、日文等)
const nonAscii = str.match(/[^\x00-\x7F]/g);
return str.length + (nonAscii ? nonAscii.length : 0);
}
// "坦克是tank的音譯" → 12 + 4 = 16
使用 Intl.Segmenter (ES2022) 或 graheme-splitter 庫按書寫字素分割,再查 eastasianwidth 資料庫。簡易版:
function getEastAsianWidth(str) {
let len = 0;
for (const ch of str) {
const code = ch.codePointAt(0);
// 簡易判斷:CJK 統一表意文字區塊、全形符號區塊等
if (
(code >= 0x3000 && code <= 0x303F) || // CJK 符號
(code >= 0x4E00 && code <= 0x9FFF) || // CJK 統一表意文字
(code >= 0xFF00 && code <= 0xFFEF) || // 全形半形
(code >= 0x20000 && code <= 0x2FFFF) // CJK 擴展
) len += 2;
else len += 1;
}
return len;
}
function getByteLength(str) {
// TextEncoder 為現代標準 API
return new TextEncoder().encode(str).length;
}
// 或手動計算(無 TextEncoder 環境)
function getByteLengthPolyfill(str) {
let len = 0;
for (let i = 0; i < str.length; i++) {
const c = str.charCodeAt(i);
if (c < 0x80) len += 1;
else if (c < 0x800) len += 2;
else if (c < 0xD800 || c >= 0xE000) len += 3; // BMP
else { i++; len += 4; } // Surrogate pair
}
return len;
}
<input id="name" maxlength="20" data-max-visual="20">
<script>
const input = document.getElementById('name');
input.addEventListener('input', () => {
const max = +input.dataset.maxVisual;
const len = getVisualLength(input.value);
if (len > max) {
input.setCustomValidity(`超過視覺長度限制 (${len}/${max})`);
} else {
input.setCustomValidity('');
}
});
</script>
明確業務定義的「長度」語意,選對計算方式,才能前後端一致、避免截斷錯誤。