PR コード スニペット

HTMLエンティティ(実体参照)を変換・デコードするスニペット【JS】

記事内に広告が含まれています。

「文字実体参照 / 数値文字参照(10進数・16進数)」をデコードするスニペットです。

数値文字参照(16進数)を置換(例:😀 → 😀)| コードスニペット【JS】

// 例: 😀 → 😀
let str = 'Hello & Welcome to <HTML> world! © 😀';

// 数値文字参照(16進数)を置換
str = str.replace(/&#x([0-9A-Fa-f]+);/g, (_, hex) => String.fromCodePoint(parseInt(hex, 16)));


/*
// 数値文字参照(16進数)を置換
str = str.replace(/&#x([0-9A-Fa-f]+);/g, function(match, hex) {
  return String.fromCodePoint(parseInt(hex, 16));
});
*/

数値文字参照(10進数)を置換(例:© → ©)| コードスニペット【JS】

// 例: © → ©
let str = 'Hello & Welcome to <HTML> world! © 😀';

// 数値文字参照(10進数)を置換
str = str.replace(/&#(\d+);/g, (_, dec) => String.fromCodePoint(parseInt(dec, 10)));


/*
// 数値文字参照(10進数)を置換
str = str.replace(/&#(\d+);/g, function(match, dec) {
  return String.fromCodePoint(parseInt(dec, 10));
});
*/

簡易版 文字実体参照を置換(例:&lt; → <)| コードスニペット【JS】

特定のコードの変換のみの簡易版。すべてのエンティティを変換するなら、他の方法の方がいい。

// 例: &lt; → <
let str = 'Hello &amp; Welcome to &lt;HTML&gt; world! &#169; &#x1F600;';

// 文字実体参照を置換
const patterns = {
  '&lt;'   : '<',
  '&gt;'   : '>',
  '&amp;'  : '&',
  '&quot;' : '"',
  '&#x27;' : '\'',
  '&#x60;' : '`'
};
str = str.replace(/&(lt|gt|amp|quot|#x27|#x60);/g, (_, entity) => patterns[`&${entity};`]);


/*
// 文字実体参照を置換
str = str.replace(/&(lt|gt|amp|quot|#x27|#x60);/g, function(match, entity) {
    return patterns['&' + entity + ';'];
});
*/

-コード, スニペット

テキストのコピーはできません。