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

瀏覽器相容性

另見