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
Patricia ArquetteOriginal
2024-12-06 03:50:14801browse

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;");
}

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;');

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!

Statement:
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