`;
});
}
public attributesHtml(attr: any) {
const output = [];
for (const n in attr) {
if (!attr.hasOwnProperty(n)) continue;
output.push(`${n}="${htmlentities(attr[n])}"`);
}
return output.join(' ');
}
public stripHtml(html: string) {
const output: string[] = [];
const tagStack: any[] = [];
const currentTag = () => {
if (!tagStack.length) return '';
return tagStack[tagStack.length - 1];
};
const disallowedTags = ['script', 'style', 'head', 'iframe', 'frameset', 'frame', 'object', 'base'];
const parser = new htmlparser2.Parser({
onopentag: (name: string) => {
tagStack.push(name.toLowerCase());
},
ontext: (decodedText: string) => {
if (disallowedTags.includes(currentTag())) return;
output.push(decodedText);
},
onclosetag: (name: string) => {
if (currentTag() === name.toLowerCase()) tagStack.pop();
},
}, { decodeEntities: true });
parser.write(html);
parser.end();
return output.join('').replace(/\s+/g, ' ');
}
}
export default new HtmlUtils();
export function plainTextToHtml(plainText: string): string {
const lines = plainText
.replace(/[\n\r]/g, '\n')
.split('\n');
const lineOpenTag = lines.length > 1 ? '' : '';
const lineCloseTag = lines.length > 1 ? '
' : '';
return lines
.map(line => lineOpenTag + escapeHtml(line) + lineCloseTag)
.join('');
}