Skip to content

Commit

Permalink
fix: enforce stricter entify behavior for textareas
Browse files Browse the repository at this point in the history
  • Loading branch information
j4w8n committed Nov 29, 2024
1 parent 94c53ff commit d8e41e6
Showing 1 changed file with 8 additions and 20 deletions.
28 changes: 8 additions & 20 deletions src/entify.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
/**
* Enforce entity characters for textarea content.
* By default, this also does basic minification before setting entities.
* For full minification, pass `minify_content` as `true`.
* To also minifiy, pass `minify` as `true`.
*
* @param {string} html The HTML string to evaluate.
* @param {boolean} [minify] Fully minifies the content of textarea elements.
Expand All @@ -11,31 +10,20 @@
* @example <textarea>3 > 2</textarea> => <textarea>3 &gt; 2</textarea>
*/
export const entify = (html, minify = false) => {
/* Trim any combination of leading line returns and/or spaces. */
html = html
.replace(/(<textarea[^>]*>)\n+/g, '$1')
.replace(/(<textarea[^>]*>)\n\s+/g, '$1')
.replace(/(<textarea[^>]*>)\s+\n/g, '$1')

/* Trim trailing spaces */
html = html.replace(/\s+<\/textarea>/g, '</textarea>')

/**
* Protect entities, inside the textarea content,
* from general minification.
* Use entities inside textarea content.
*/
html = html.replace(/<textarea[^>]*>((.|\n)*?)<\/textarea>/g, (match, capture) => {
return match.replace(capture, (match) => {
return match
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/\//g, '&#47;')
.replace(/"/g, '&#34;')
.replace(/'/g, '&#39;')
.replace(/\n/g, '&#13;')
.replace(/%/g, '&#37;')
.replace(/\{/g, '&#123;')
.replace(/\}/g, '&#125;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&apos;')
.replace(/\n/g, '&#10;')
.replace(/\r/g, '&#13;')
.replace(/\s/g, '&nbsp;')
})
})

Expand Down

0 comments on commit d8e41e6

Please sign in to comment.