Home > Web Front-end > JS Tutorial > How Can I Safely Escape HTML Special Characters in JavaScript?

How Can I Safely Escape HTML Special Characters in JavaScript?

Patricia Arquette
Release: 2024-12-06 03:50:14
Original
819 people have browsed it

How Can I Safely Escape HTML Special Characters in JavaScript?

Escaping 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, "&")
    .replace(/</g, "&amp;lt;")
    .replace(/>/g, "&amp;gt;")
    .replace(/&quot;/g, "&amp;quot;")
    .replace(/'/g, "&amp;#039;");
}
Copy after login

For modern browsers, you can leverage the replaceAll() function for a more concise solution:

const escapeHtml = unsafe => unsafe
  .replaceAll('&amp;', '&amp;amp;')
  .replaceAll('<', '&amp;lt;')
  .replaceAll('>', '&amp;gt;')
  .replaceAll('&quot;', '&amp;quot;')
  .replaceAll("'", '&amp;#039;');
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template