(string: unknown)
| 1 | const escapeRE = /["'&<>]/ |
| 2 | |
| 3 | export function escapeHtml(string: unknown): string { |
| 4 | const str = '' + string |
| 5 | const match = escapeRE.exec(str) |
| 6 | |
| 7 | if (!match) { |
| 8 | return str |
| 9 | } |
| 10 | |
| 11 | let html = '' |
| 12 | let escaped: string |
| 13 | let index: number |
| 14 | let lastIndex = 0 |
| 15 | for (index = match.index; index < str.length; index++) { |
| 16 | switch (str.charCodeAt(index)) { |
| 17 | case 34: // " |
| 18 | escaped = '"' |
| 19 | break |
| 20 | case 38: // & |
| 21 | escaped = '&' |
| 22 | break |
| 23 | case 39: // ' |
| 24 | escaped = ''' |
| 25 | break |
| 26 | case 60: // < |
| 27 | escaped = '<' |
| 28 | break |
| 29 | case 62: // > |
| 30 | escaped = '>' |
| 31 | break |
| 32 | default: |
| 33 | continue |
| 34 | } |
| 35 | |
| 36 | if (lastIndex !== index) { |
| 37 | html += str.slice(lastIndex, index) |
| 38 | } |
| 39 | |
| 40 | lastIndex = index + 1 |
| 41 | html += escaped |
| 42 | } |
| 43 | |
| 44 | return lastIndex !== index ? html + str.slice(lastIndex, index) : html |
| 45 | } |
| 46 | |
| 47 | // https://www.w3.org/TR/html52/syntax.html#comments |
| 48 | const commentStripRE = /^-?>|<!--|-->|--!>|<!-$/g |
no outgoing calls