用 JavaScript 的 charAt() 和 charCodeAt() 读取字符和编码值

charAt(index) 将一个 UTF-16 码元作为字符串返回。charCodeAt(index) 返回它的数值。索引从 0 开始。🙂 这类表情符号需要两个码元,因此单次调用其中任一方法都无法读取完整表情。

把单个码元读取为字符串或数字

UTF-16(16 位 Unicode 转换格式)的每个码元是一个 16 位值。在控制台运行代码,abcde 的索引 3 会得到 'd' 和 100。参见 ECMAScript: charAt() 和 ECMAScript: charCodeAt()。

const text = 'abcde';
console.log(text.charAt(3));     // 'd'
console.log(text.charCodeAt(3)); // 100
console.log(text.length);        // 5

比较索引越界的返回值

索引转为整数后,如果小于 0 或不小于 length,charAt() 返回空字符串,charCodeAt() 返回 NaN。示例中的 text[10] 返回 undefined。用 text.at(-1) 可以读取最后一个码元。

const text = 'abcde';
console.log(text.charAt(10));     // ''
console.log(text.charCodeAt(10)); // NaN
console.log(text[10]);            // undefined
console.log(Number.isNaN(text.charCodeAt(10))); // true
console.log(text.at(-1));       // 'e'
console.log(text.charAt(3.9)); // 'd'

用 Number.isNaN() 判断数字结果。NaN === NaN 为假。方法会向零截断小数索引,因此 charAt(3.9) 与 charAt(3) 相同。如果输入必须是整数,请在调用前检查。

区分表情符号的码元与码点

🙂 的码点是 U+1F642。它在 UTF-16 中用一对代理码元表示,所以 length 为 2。索引 0 的 codePointAt() 合并两个码元,返回 128578。索引 1 从后半部分开始,返回 56898。参见 ECMAScript: codePointAt()。

const face = String.fromCodePoint(0x1F642);
console.log(face.length);          // 2
console.log(face.charAt(0).length); // 1
console.log(face.charCodeAt(0));   // 55357
console.log(face.codePointAt(0));  // 128578
console.log(face.charCodeAt(1));  // 56898
console.log(face.codePointAt(1)); // 56898
console.log([...face].length);   // 1

codePointAt() 的参数仍是 UTF-16 索引。按码点遍历时,for...of 会一起读取一对代理码元。如果需要处理视觉上的一个字符,如组合字符或表情序列,可以采用 Intl.Segmenter 的 granularity: 'grapheme'。

完整示例:修改字符串和索引

将 HTML 以 UTF-8 保存为 string-character-code.html 并打开。初始字符串在索引 3 处得到 "d"、100 和 100。输入 10 后会看到 ""、NaN 和 undefined。

<!doctype html>
<html lang="zh">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>读取字符串位置和编码值</title>
</head>
<body>
<label for="text">字符串</label>
<input id="text" type="text" value="abcde">
<label for="index">UTF-16 索引</label>
<input id="index" type="number" min="0" step="1" value="3">
<pre id="output" aria-live="polite"></pre>
<script>
const text = document.querySelector('#text');
const index = document.querySelector('#index');
const output = document.querySelector('#output');

function show() {
  const value = text.value;
  const position = index.valueAsNumber;
  if (!Number.isSafeInteger(position) || position < 0) {
    output.textContent = "请输入非负的安全整数索引。";
    return;
  }
  const unit = value.charCodeAt(position);
  const point = value.codePointAt(position);
  output.textContent = `字符串长度(UTF-16 码元): ${value.length}\n` +
    `charAt(${position}): ${JSON.stringify(value.charAt(position))}\n` +
    `charCodeAt(${position}): ${Number.isNaN(unit) ? 'NaN' : unit}\n` +
    `codePointAt(${position}): ${point === undefined ? 'undefined' : point}`;
}

text.addEventListener('input', show);
index.addEventListener('input', show);
show();
</script>
</body>
</html>

只输入 🙂,比较索引 0 与 1。通过 JSON.stringify(),两次 charAt() 的结果显示为 "\ud83d" 与 "\ude42"。示例只接受非负的安全整数索引。