LoginSignup
5
6

More than 1 year has passed since last update.

【絵文字】JavaScriptでサロゲートペアを含む文字列をHTML Entityに変換する

Last updated at Posted at 2020-02-10

HTML Entityへ変換

通常の文字列ならcharCodeAtで解決できますが、サロゲートペアは文字が崩れてしまうのでcodePointAtを利用します。

function convert(value) {
  return [...value].map((word) => {
    return `&#x${word.codePointAt(0).toString(16)};`;
  }).join('');
}

Example

const result = convert('😇')

console.log(result); // > 😇
<p>こんにちは&#x1f607;</p>  // こんにちは😇

HTML Entityから元に戻す

復元する場合はString.fromCharCodeの代わりにString.fromCodePointを利用します。

function revert(str) {
  return str.replace(/&#(.*?);/g, (_, p1) => String.fromCodePoint(`0${p1}`));
}

Example

const result = revert('こんにちは&#x1f607;&#x1f607;&#x1f607;&#x1f607;');

console.log(result); // > こんにちは😇😇😇😇

HTML Entityとは

HTML エンティティとは、アンパサンド (&) で始まりセミコロン (;)で終わるテキスト (文字列) のひと固まりです。エンティティは(通常は HTML コードとして解釈される)予約済み文字や、(ノーブレークスペースのように) 見えない文字を表示するためによく使用されます。標準キーボードでは入力が難しい文字の代わりに使用することもできます。

https://developer.mozilla.org/ja/docs/Glossary/Entity より引用

何がうれしいの?

CMSなどにHTMLを直接入力できるような状況なら、CMSがサロゲートペアに対応していない場合でも絵文字を出力させることができるようになります。

参考文献

5
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
6