@tiptap/core
Version:
headless rich text editor
27 lines (25 loc) • 1.07 kB
text/typescript
/**
* Decode common HTML entities in text content so they display as literal
* characters inside the editor. The decode order matters: `&` must be
* decoded **last** so that doubly-encoded sequences like `<` first
* survive the `<` pass and then correctly become `<` (not `<`).
*/
export function decodeHtmlEntities(text: string): string {
return text
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/&/g, '&')
}
/**
* Encode HTML special characters so they roundtrip safely through markdown.
* `&` is encoded **first** to avoid double-encoding the ampersand in other
* entities (e.g. `<` → `<`, not `&lt;`).
*
* Note: `"` is intentionally NOT encoded here because double quotes are
* ordinary characters in markdown and do not need escaping. The decode
* function still handles `"` because the markdown tokenizer may emit it.
*/
export function encodeHtmlEntities(text: string): string {
return text.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>')
}