Language
string: length は UTF-16 のコード単位を数える
絵文字などの補助文字は UTF-16 で 2 単位になり、見た目の文字数と length が一致しないことがあります。
SourceunicodeLengths.ts
Node.js 22
export function codePointLength(value: string): number {
return Array.from(value).length;
}TestunicodeLengths.test.ts
Node.js 22
import assert from "node:assert/strict";
import test from "node:test";
import { codePointLength } from "../../src/string/unicodeLengths.js";
test("絵文字はlengthでは2だがArrayFromでは1になる", () => {
assert.equal("🚀".length, 2);
assert.equal(codePointLength("🚀"), 1);
});01Assertion
このテストで確認できること
- ロケット絵文字の length は 2 になる
- Array.from による code point 列の長さは 1 になる
UI 上の文字数制限や文字単位の切り詰めでは、UTF-16 コード単位と利用者が認識する文字の差を意識します。
OBSERVED RESULT
expected: "🚀".length → 2
actual: 2
expected: Array.from("🚀").length → 1