String.fromCharCode()との違いは? String.fromCodePoint()を使いこなそう
String.fromCodePoint()
は、JavaScript で Unicode コードポイント のシーケンスを文字列に変換するために使用されるメソッドです。これは、String.fromCharCode()
メソッドと似ていますが、String.fromCodePoint()
は 補助文字 (BMP より大きいコードポイントを持つ文字) を扱うことができます。
使い方
String.fromCodePoint()
メソッドは、1 つ以上のコードポイント引数を取ります。各引数は、Unicode コードポイントを表す整数値です。メソッドは、引数で指定されたコードポイントに対応する文字列を返します。
const emoji = String.fromCodePoint(0x1F60A); // という絵文字を生成
console.log(emoji); //
String.fromCharCode()
との違い
String.fromCharCode()
メソッドは、String.fromCodePoint()
メソッドと似ていますが、補助文字 を扱うことはできません。String.fromCharCode()
メソッドは、基本多言語面 (BMP) 内のコードポイントのみを扱うことができます。BMP は、Unicode コード空間の最初の 65,536 個のコードポイントを含む領域です。
補助文字を扱う必要がある場合は、String.fromCodePoint()
メソッドを使用する必要があります。
例
以下の例では、String.fromCodePoint()
メソッドを使用して、ハート () と星の絵文字 () を生成します。
const heart = String.fromCodePoint(0x1F49C);
const star = String.fromCodePoint(0x2605);
console.log(heart); //
console.log(star); //
String.fromCodePoint()
メソッドは、引数として任意の数のコードポイントを受け取ることができます。String.fromCodePoint()
メソッドは、静的メソッドです。つまり、新しいインスタンスを作成せずに呼び出すことができます。String.fromCodePoint()
メソッドは、ES6 で導入されました。
例 1:ハートと星の絵文字を生成する
const heart = String.fromCodePoint(0x1F49C);
const star = String.fromCodePoint(0x2605);
console.log(heart); //
console.log(star); //
例 2:U+2161 で表されるギリシャ文字デルタを生成する
const delta = String.fromCodePoint(0x2161);
console.log(delta); // Δ
例 3:U+1F64F で表されるニッコリ笑顔の絵文字を生成する
const smiley = String.fromCodePoint(0x1F64F);
console.log(smiley); //
const name = String.fromCodePoint(0x48, 0x65, 0x6C, 0x6C, 0x6F);
console.log(name); // Hello
文字列リテラル
最も一般的で簡単な方法は、文字列リテラル を使用することです。文字列リテラルは、引用符で囲まれた一連の文字です。
const hello = "こんにちは"; const world = "世界"; console.log(hello + " " + world); // こんにちは 世界
String コンストラクタ
String
コンストラクタを使用して、文字列を作成することもできます。const greeting = new String("おはよう"); console.log(greeting); // おはよう
テンプレートリテラル
テンプレートリテラル は、バッククォート (
) で囲まれた文字列リテラルです。変数や式を文字列に埋め込むことができます。
const name = "山田"; const message = `こんにちは、${name} さん!`; console.log(message); // こんにちは、山田 さん!
数値の変換
toString()
メソッドを使用して、数値を文字列に変換することもできます。const age = 30; const message = "私の年齢は " + age + " 歳です。"; console.log(message); // 私の年齢は 30 歳です。
上記以外にも、String.fromCharCode()
メソッドや charCodeAt()
メソッドを使用して、個々の文字コードから文字列を作成する方法もあります。
どの方法を使用すべきか
使用する方法は、状況によって異なります。
- 数値の変換は、数値を文字列として表示する必要がある場合に使用します。
String
コンストラクタは、より高度な文字列操作が必要な場合に使用できます。- テンプレートリテラルは、変数や式を文字列に埋め込む必要がある場合に便利です。
- 文字列リテラルは、最も一般的で簡単な方法です。