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.
Run const escapeHtml = unsafe => {
return unsafe
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''')
;
};
console.log(escapeHtml('<foo bar="baz">&</foo>')); // <foo bar="baz">&</foo>
If you need to populate a dom node with escaped html, you can simply use textContent instead of innerHTML.
Run 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);
Reset Run example above to see the output.
There is also built in methods for URL encoding of strings. encodeURI and encodeURIComponent respectively.
Run // 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