[Edit]
+
0
-
0

Node.js - escape HTML special characters

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
// Note: in this snippet you can find quite optimal solution to escape HTML special characters. // Hint: you can try to speed up source code much more by updating `escapeHtml()` function. // // from: // ``` // for (const character of html) { // ... // ``` // // to: // ``` // for (let i = 0; i < html.length; ++i) { // const character = html[i]; // ... // ``` const escapeHtml = (html) => { let result = ''; for (const character of html) { switch (character) { // Warning: do not change cases order case '&': result += '&amp;'; break; case '<': result += '&lt;'; break; case '>': result += '&gt;'; break; case '"': result += '&quot;'; break; case '\'': result += '&#039;'; break; default: result += character; } } return result; }; // Usage example: console.log(escapeHtml('<div class="message">Hi!</div>')); // &lt;div class=&quot;message&quot;&gt;Hi!&lt;/div&gt; // Output: // // &lt;div class=&quot;message&quot;&gt;Hi!&lt;/div&gt; // See also: // // 1. https://dirask.com/snippets/Node-js-escape-HTML-special-characters-DKgEnD
Reset