Sometimes, we want to escape HTML with JavaScript.
In this article, we’ll look at how to escape HTML with JavaScript.
How to escape HTML with JavaScript?
To escape HTML with JavaScript, we can put the HTML string in an element.
Then we can get the escaped string from the innerHTML
property.
For instance, we write:
const escapeHTML = (str) => {
const p = document.createElement("p");
p.appendChild(document.createTextNode(str));
return p.innerHTML;
}
const escaped = escapeHTML('Test & Sample')
console.log(escaped)
to define the escapeHTML
function that takes the str
string as a parameter.
In it, we create a p element with createElement
.
Then we call appendChild
with the text node that we create from str
with createTextNode
.
Finally, we return the innerHTML
property to return the escaped string.
Therefore, escaped
is 'Test & Sample'
.
Conclusion
To escape HTML with JavaScript, we can put the HTML string in an element.
Then we can get the escaped string from the innerHTML
property.