I want to display a text to HTML by a javascript function. How can I escape html special chars in JS? Is there an API ?
This is, by far, the fastest way I have seen it done. Plus, it does it all without adding, removing, or changing elements on the page.
function escapeHTML(unsafeText) {
let div = document.createElement('div');
div.innerText = unsafeText;
return div.innerHTML;
}
The most concise and performant way to display unencoded text is to use textContent
property.
Faster than using innerHTML
. And that's without taking into account escaping overhead.
document.body.textContent = 'a <b> c </b>';
It was interesting to find a better solution:
var escapeHTML = function(unsafe) {
return unsafe.replace(/[&<"']/g, function(m) {
switch (m) {
case '&':
return '&';
case '<':
return '<';
case '"':
return '"';
default:
return ''';
}
});
};
I do not parse >
because it does not break XML/HTML code in the result.
Here are the benchmarks: http://jsperf.com/regexpairs
Also, I created a universal escape
function: http://jsperf.com/regexpairs2
Came across this issue when building a DOM structure. This question helped me solve it. I wanted to use a double chevron as a path separator, but appending a new text node directly resulted in the escaped character code showing, rather than the character itself:
var _div = document.createElement('div');
var _separator = document.createTextNode('»');
//_div.appendChild(_separator); /* this resulted in '»' being displayed */
_div.innerHTML = _separator.textContent; /* this was key */
function escapeHtml(html){
var text = document.createTextNode(html);
var p = document.createElement('p');
p.appendChild(text);
return p.innerHTML;
}
// Escape while typing & print result
document.querySelector('input').addEventListener('input', e => {
console.clear();
console.log( escapeHtml(e.target.value) );
});
<input style='width:90%; padding:6px;' placeholder='<b>cool</b>'>
Using lodash
_.escape('fred, barney, & pebbles');
// => 'fred, barney, & pebbles'
source code