import htmlEntities from './html-entities.js';
export function decodeHTMLEntities(str) {
return str.replace(/&(#\d+|#x[a-f0-9]+|[a-z]+\d*);?/gi, (match, entity) => {
if (typeof htmlEntities[match] === 'string') {
return htmlEntities[match];
}
if (entity.charAt(0) !== '#' || match.charAt(match.length - 1) !== ';') {
// keep as is, invalid or unknown sequence
return match;
}
let codePoint;
if (entity.charAt(1) === 'x') {
// hex
codePoint = parseInt(entity.substr(2), 16);
} else {
// dec
codePoint = parseInt(entity.substr(1), 10);
}
let output = '';
if ((codePoint >= 0xd800 && codePoint <= 0xdfff) || codePoint > 0x10ffff) {
// Invalid range, return a replacement character instead
return '\uFFFD';
}
if (codePoint > 0xffff) {
codePoint -= 0x10000;
output += String.fromCharCode(((codePoint >>> 10) & 0x3ff) | 0xd800);
codePoint = 0xdc00 | (codePoint & 0x3ff);
}
output += String.fromCharCode(codePoint);
return output;
});
}
export function escapeHtml(str) {
return str.trim().replace(/[<>"'?&]/g, c => {
let hex = c.charCodeAt(0).toString(16);
if (hex.length < 2) {
hex = '0' + hex;
}
return '' + hex.toUpperCase() + ';';
});
}
export function textToHtml(str) {
let html = escapeHtml(str).replace(/\n/g, '
');
return '