LoginSignup
2

More than 5 years have passed since last update.

js HTML Entitiesへの変換

Last updated at Posted at 2017-01-06

お題

HTMLマークアップにおいて頻繁に用いられると思われる文字(下記)をHTML Entities(文字実体参照)へ変換する。

文字 文字実体参照 説明
< &lt; 小なり記号(半角)
> &gt; 大なり記号(半角)
& &amp; アンパサンド(半角)
" &quot; 二重引用符(半角)
' &apos; 引用符(半角)

*HTML Entities

function convertHTML(str) {
  htmlEntities={
    '&':'&amp;',
    '<':'&lt;',
    '>':'&gt;',
    '\"':'&quot;',
    '\'':"&apos;"
  };
//write your code
}
convertHTML("Dolce & Gabbana");//Dolce &​amp; Gabbana

出力結果 例

convertHTML('Stuff in "quotation marks"') // Stuff in &​quot;quotation marks&​quot;
convertHTML("Shindler's List") // Shindler&​apos;s List
convertHTML("<>") // &​lt;&​gt;
convertHTML("abc") // abc

使ったもの

split()
map()
join()

考えかた

・変換する文字と文字実体参照をオブジェクトで用意する。
・split()で分割した引数をmap()で個別に変換する。
割り当てた文字に該当するものがあれば変換し、なければそのまま返す。
・さいごにjoin()で一緒にしておわり

コード

function convertHTML(str) {
  htmlEntities={
    '&':'&amp;',
    '<':'&lt;',
    '>':'&gt;',
    '\"':'&quot;',
    '\'':"&apos;"
  };
  return str.split('').map(function(entity){
    return htmlEntities[entity] || entity;
  }).join('');
}

正規表現を使ったコード

function convertHTML(str) {
  str = str.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;').replace(/'/g,"&apos;");
return str;
}

他にもコードが浮かんだ方、コメントおまちしております。

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