「文字実体参照 / 数値文字参照(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));
});
*/
簡易版 文字実体参照を置換(例:<
→ <)| コードスニペット【JS】
特定のコードの変換のみの簡易版。すべてのエンティティを変換するなら、他の方法の方がいい。
// 例: < → <
let str = 'Hello & Welcome to <HTML> world! © 😀';
// 文字実体参照を置換
const patterns = {
'<' : '<',
'>' : '>',
'&' : '&',
'"' : '"',
''' : '\'',
'`' : '`'
};
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 + ';'];
});
*/