String.fromCodePoint()

Baseline 已广泛支持

此特性已相当成熟,可在许多设备和浏览器版本上使用。自 2015 年 9 月以来,该特性已在各大浏览器中可用。

String.fromCodePoint() 静态方法返回一个由指定码点序列创建的字符串。

试一试

console.log(String.fromCodePoint(9731, 9733, 9842, 0x2f804));
// Expected output: "☃★♲你"

语法

js
String.fromCodePoint()
String.fromCodePoint(num1)
String.fromCodePoint(num1, num2)
String.fromCodePoint(num1, num2, /* …, */ numN)

参数

num1, …, numN

一个介于 00x10FFFF(包含)之间的整数,代表一个 Unicode 码点。

返回值

一个由指定的码点序列创建的字符串。

异常

RangeError

如果 numN 不是整数,小于 0,或者在转换为数字后大于 0x10FFFF,则抛出该错误。

描述

因为 fromCodePoint()String 的一个静态方法,所以你总是使用 String.fromCodePoint() 的方式调用它,而不是作为你创建的 String 值的某个方法来调用。

Unicode 码点的范围是从 01114111 (0x10FFFF)。在 UTF-16 中,每个字符串索引都是一个值为 065535 的码单元。较高的码点由一对 16 位代理伪字符表示。因此,fromCodePoint() 返回的字符串的 length(以 UTF-16 码单元计)可能大于传入的参数数量。有关 Unicode 的信息,请参阅 UTF-16 字符、Unicode 码点和字位簇

示例

使用 fromCodePoint()

有效输入

js
String.fromCodePoint(42); // "*"
String.fromCodePoint(65, 90); // "AZ"
String.fromCodePoint(0x404); // "\u0404" === "Є"
String.fromCodePoint(0x2f804); // "\uD87E\uDC04"
String.fromCodePoint(194564); // "\uD87E\uDC04"
String.fromCodePoint(0x1d306, 0x61, 0x1d307); // "\uD834\uDF06a\uD834\uDF07"

无效输入

js
String.fromCodePoint("_"); // RangeError
String.fromCodePoint(Infinity); // RangeError
String.fromCodePoint(-1); // RangeError
String.fromCodePoint(3.14); // RangeError
String.fromCodePoint(3e-2); // RangeError
String.fromCodePoint(NaN); // RangeError

与 fromCharCode() 比较

String.fromCharCode() 无法通过指定补充字符(即码点 0x0100000x10FFFF)来返回它们。相反,它需要 UTF-16 代理对才能返回补充字符。

js
String.fromCharCode(0xd83c, 0xdf03); // Code Point U+1F303 "Night with
String.fromCharCode(55356, 57091); // Stars" === "\uD83C\uDF03"

另一方面,String.fromCodePoint() 可以通过指定其码点(等同于 UTF-32 码单元)来返回 4 字节的补充字符,以及更常见的 2 字节 BMP 字符。

js
String.fromCodePoint(0x1f303); // or 127747 in decimal

规范

规范
ECMAScript® 2026 语言规范
# sec-string.fromcodepoint

浏览器兼容性

另见