html escape

When working with web development there is often a need to convert special characters in different ways.

A simple replace function to replace special characters with their entity representations.

const escapeHtml = unsafe => { return unsafe .replace(/&/g, '&amp;') .replace(/</g, '&lt;') .replace(/>/g, '&gt;') .replace(/"/g, '&quot;') .replace(/'/g, '&#039;') ; }; console.log(escapeHtml('<foo bar="baz">&</foo>')); // &lt;foo bar=&quot;baz&quot;&gt;&amp;&lt;/foo&gt;

If you need to populate a dom node with escaped html, you can simply use textContent instead of innerHTML.

document.getElementById('result1').textContent = ''; let line1 = document.createElement('div'); let line2 = document.createElement('div'); line1.innerHTML = '<b>Bold text</b>'; line2.textContent = '<b>Bold text</b>'; document.getElementById('result1').appendChild(line1); document.getElementById('result1').appendChild(line2);
Run example above to see the output.

There is also built in methods for URL encoding of strings. encodeURI and encodeURIComponent respectively.

// Encoding a complete URI will not escape url components like = and &. console.log(encodeURI('<foo bar="baz">&</foo>')); // %3Cfoo%20bar=%22baz%22%3E&%3C/foo%3E // To encode all special characters: console.log(encodeURIComponent('<foo bar="baz">&</foo>')); // %3Cfoo%20bar%3D%22baz%22%3E%26%3C%2Ffoo%3E