Home >Web Front-end >JS Tutorial >How Can I Safely Escape HTML Special Characters in JavaScript?
In web development, displaying untrusted text in HTML can lead to security vulnerabilities. To prevent these, it's crucial to escape special characters that may interfere with the HTML structure. JavaScript offers several ways to achieve this.
One approach is to use the venerable replace() function, as seen in the following code snippet:
function escapeHtml(unsafe) { return unsafe .replace(/&/g, "&amp;") .replace(/</g, "&lt;") .replace(/>/g, "&gt;") .replace(/"/g, "&quot;") .replace(/'/g, "&#039;"); }
For modern browsers, you can leverage the replaceAll() function for a more concise solution:
const escapeHtml = unsafe => unsafe .replaceAll('&', '&amp;') .replaceAll('<', '&lt;') .replaceAll('>', '&gt;') .replaceAll('"', '&quot;') .replaceAll("'", '&#039;');
By implementing these escape mechanisms, you ensure that untrusted text is rendered correctly and safely, minimizing the risk of malicious attacks.
The above is the detailed content of How Can I Safely Escape HTML Special Characters in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!