LoginSignup
2

More than 3 years have passed since last update.

文字列をHTML数値文字参照とCSS数値文字参照に変換する

Last updated at Posted at 2018-05-22

はじめに

CSS用(backgroundのcontent)の数値文字参照を一発で出してくれるツールがすぐ見つけられなかったので作るついでにサロゲートペアに対応した状態にしました。💪とかも大丈夫です。

下記に変換ツールを公開しています!
文字列→数値文字参照ツール

この記事は変換部分だけ紹介しています。

実装

文字列→HTML数値文字参照

function stringToHtmlNumCharRef(string){
    let result = "";

    for(let val of string){
      result += "&#x" + val.codePointAt(0).toString(16) + ";";
    }

    return result;
}

文字列→CSS数値文字参照

function stringToCssNumCharRef(string){
  let result = "";

  for(let val of string){
    result += "\\" + val.codePointAt(0).toString(16);
  }

  return result;
}

解説

for...of文とcodePointAtがサロゲートペアに対応してるので、1文字ずつ16進数に変換してそれに必要な文字列をくっつけるだけです。

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
2