The HTML string to convert
The ASCII string
htmlToAscii("<h2>Title</h2><p>Hello <b>world</b></p><ul><li>one</li><li>two</li></ul>")
// Returns "Title\nHello world\none\ntwo"
export function htmlToAscii(html: string): string {
return (
html
.replace(BLOCK_CLOSE_REGEX, '\n')
.replace(/<br\s*\/?>/gi, '\n')
.replace(/<[^>]+>/g, '')
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/ /g, ' ')
.replace(/"/g, '"')
.replace(/'/g, "'")
// Trim trailing spaces per line and collapse blank-line runs from empty blocks.
.replace(/[ \t]+\n/g, '\n')
.replace(/\n{2,}/g, '\n')
.trim()
);
}
Converts HTML to ASCII. Closing block-level tags (paragraphs, headings, list items, table rows/cells, …) and
<br>become line breaks; every other tag is stripped and the common HTML entities are decoded. Runs of blank lines left by empty or nested blocks are collapsed to a single line break.