length 是字串實例的唯讀屬性,回傳 UTF-16 代碼單元數量(非字元數)。對於 BMP 字元(基本多文種平面)一對一,但增補字元(Emoji、罕用漢字)佔 2 個代碼單元,導致長度計算與直觀字元數不符。
<script>
const str = 'Hello World';
console.log(str.length); // 11
const empty = '';
console.log(empty.length); // 0
</script>
<script>
const emoji = '😀'; // U+1F600
console.log(emoji.length); // 2 (UTF-16 代理對)
const str = 'A😀B';
console.log(str.length); // 4
console.log([...str].length); // 3 (真實字元數)
console.log(Array.from(str).length); // 3
// 正確取得字元數
function charCount(str) {
return [...str].length; // 或 Array.from(str).length
}
</script>
function safeSlice(str, maxChars) {
const arr = [...str];
return arr.length > maxChars ? arr.slice(0, maxChars).join('') + '…' : str;
}
console.log(safeSlice('Hello😀World', 8)); // "Hello😀W…" (正確 8 字元)
length 回傳 UTF-16 代碼單元數。處理可能含 Emoji/增補字元的字串時,請使用展開運算子 `[...str]` 或 `Array.from(str)` 取得真實字元數與安全迭代。