I want to display text to HTML by a JavaScript function. How can I escape HTML special characters in JavaScript? Is there an API?
Skipping > can potentially break code. You must keep in mind that inside the <> is also html. In that case skipping > will break. If you're only escaping for between tags then you probably only need escape < and &.
We can escape the HTML of the string using the replace method of the string.
Using the Escape Character ( \ ) We can use the backslash ( \ ) escape character to prevent JavaScript from interpreting a quote as the end of the string. The syntax of \' will always be a single quote, and the syntax of \" will always be a double quote, without any fear of breaking the string.
Here's a solution that will work in practically every web browser:
function escapeHtml(unsafe) { return unsafe .replace(/&/g, "&") .replace(/</g, "<") .replace(/>/g, ">") .replace(/"/g, """) .replace(/'/g, "'"); }
If you only support modern web browsers (2020+), then you can use the new replaceAll function:
const escapeHtml = (unsafe) => { return unsafe.replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>').replaceAll('"', '"').replaceAll("'", '''); }
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>'>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With