JavaScript fromCharCode() 将 UTF-16 代码单元转换为字符串

在 JavaScript 中,String.fromCharCode(72, 73) 可以用 UTF-16 代码单元的数值生成字符串 HI。如果已知的是一个 Unicode 码点,例如 U+1F642,则用 String.fromCodePoint(0x1F642)。

将数字转换为 UTF-16 代码单元

fromCharCode() 是 String 的静态方法。每个参数按顺序生成一个 16 位代码单元。没有参数时返回空字符串。若要读回某个代码单元的数值,可使用 charCodeAt()。ECMAScript · String.fromCharCode()

console.log(String.fromCharCode(72)); // 'H'
console.log(String.fromCharCode(72, 69, 76, 76, 79)); // 'HELLO'
console.log('H'.charCodeAt(0)); // 72
console.log(String.fromCharCode(72, 73)); // 'HI'
console.log(String.fromCharCode());       // ''

区分代码单元和码点

Unicode 码点是 Unicode 分配的编号,UTF-16 代码单元是表示文本的 16 位数值。例如,U+1F642 需要 0xD83D 和 0xDE42。这两个单元按顺序组成一个代理对。

const point = 0x1F642;
const face = String.fromCodePoint(point);
console.log(face.length); // 2
console.log(face.charCodeAt(0)); // 55357
console.log(face.charCodeAt(1)); // 56898
console.log(String.fromCharCode(55357, 56898) === face); // true
console.log(String.fromCharCode(point) === face); // false
console.log(String.fromCharCode(0xD83D, 0xDE42) === face); // true

如果已经有这两个代码单元,可以一起传给 fromCharCode()。单独传入高位或低位代理项会留下一个未配对的单元。如果已知的是码点,fromCodePoint() 会生成所需的 UTF-16 代码单元。它接受 0 到 0x10FFFF 之间的整数。ECMAScript · String.fromCodePoint()

在转换前验证数字输入

对于普通数值,fromCharCode() 会截去小数部分,并将结果按 16 位范围取模。比如 65536 变成 0,-1 变成 65535,72.9 变成 72。如果要求输入是代码单元,请在转换前确认它是 0 到 65535 之间的整数。

console.log(String.fromCharCode(65536).charCodeAt(0)); // 0
console.log(String.fromCharCode(-1).charCodeAt(0));    // 65535
console.log(String.fromCharCode(72.9).charCodeAt(0));  // 72

function codeUnitToText(value) {
  if (!Number.isInteger(value) || value < 0 || value > 65535) {
    throw new RangeError("请输入有效的 UTF-16 代码单元。");
  }
  return String.fromCharCode(value);
}
console.log(codeUnitToText(72)); // 'H'

从文本读取数值时,应先确定允许的数字格式。下面的示例接受十进制整数和以 0x 开头的十六进制整数,拒绝空项、小数、负数和超出范围的值。代理项是否正确配对需要另外验证。

生成字符串并读回代码单元

用 UTF-8 编码将代码保存为 string-from-char-code.html,然后在浏览器中打开。默认列表会生成 HELLO。输入 65, 66 并点击按钮,可以看到 AB 和读回的数值 65, 66。

<!doctype html>
<html lang="zh">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>用 UTF-16 代码单元生成字符串</title>
</head>
<body>
<label for="units">UTF-16 代码单元(用逗号分隔)</label>
<input id="units" type="text" value="72, 69, 76, 76, 79">
<button id="convert" type="button">生成字符串</button>
<pre id="output" aria-live="polite"></pre>
<script>
const units = document.querySelector('#units');
const output = document.querySelector('#output');

function convert() {
  const parts = units.value.split(',').map(part => part.trim());
  const values = parts.map(part => Number(part));
  if (parts.some(part => !/^(?:[0-9]+|0x[0-9a-f]+)$/i.test(part)) ||
      values.some(value => !Number.isInteger(value) || value < 0 || value > 65535)) {
    output.textContent = "请输入 0 到 65535 的十进制或 0x 十六进制整数,并用逗号分隔。";
    return;
  }
  const text = values.map(value => String.fromCharCode(value)).join('');
  output.textContent = `字符串: ${JSON.stringify(text)}\n` +
    `读回的 UTF-16 数值: ${Array.from({ length: text.length },
      (_, index) => text.charCodeAt(index)).join(', ')}`;
}

document.querySelector('#convert').addEventListener('click', convert);
convert();
</script>
</body>
</html>

输入 0xD83D, 0xDE42,会显示 🙂 和十进制代码单元 55357, 56898。输入 65536 或 65,,66 可查看提示。