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 ?
function escapeHtml(unsafe) {
return unsafe
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}
If you already use modules in your app, you can use escape-html module.
import escapeHtml from 'escape-html';
const unsafeString = '<script>alert("XSS");</script>';
const safeString = escapeHtml(unsafeString);
I think I found the proper way to do it...
// Create a DOM Text node:
var text_node = document.createTextNode(unescaped_text);
// Get the HTML element where you want to insert the text into:
var elem = document.getElementById('msg_span');
// Optional: clear its old contents
//elem.innerHTML = '';
// Append the text node into it:
elem.appendChild(text_node);
Try this, using the prototype.js
library:
string.escapeHTML();
Try a demo
DOM Elements support converting text to HTML by assigning to innerText. innerText is not a function but assigning to it works as if the text were escaped.
document.querySelectorAll('#id')[0].innerText = 'unsafe " String >><>';
You can use jQuery's .text() function.
For example:
http://jsfiddle.net/9H6Ch/
From the jQuery documentation regarding the .text()
function:
We need to be aware that this method escapes the string provided as necessary so that it will render correctly in HTML. To do so, it calls the DOM method .createTextNode(), does not interpret the string as HTML.
Previous Versions of the jQuery Documentation worded it this way (emphasis added):
We need to be aware that this method escapes the string provided as necessary so that it will render correctly in HTML. To do so, it calls the DOM method .createTextNode(), which replaces special characters with their HTML entity equivalents (such as &lt; for <).