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

How Do I Escape HTML Special Characters in JavaScript?

DDD
DDDOriginal
2024-12-06 01:40:10336browse

How Do I Escape HTML Special Characters in JavaScript?

Escaping HTML Special Characters in JavaScript

When displaying text in HTML using JavaScript functions, it's crucial to escape HTML special characters to prevent errors and unexpected behavior. The special characters you need to escape include & (ampersand), < (less than), > (greater than), " (double quote), and ' (single quote).

Escaping HTML Special Characters Using a Function

Fortunately, JavaScript provides an easy way to escape these special characters using the following function:

function escapeHtml(unsafe) {
  return unsafe
    .replace(/&amp;/g, "&amp;amp;")
    .replace(/</g, "&amp;lt;")
    .replace(/>/g, "&amp;gt;")
    .replace(/&quot;/g, "&amp;quot;")
    .replace(/'/g, "&amp;#039;");
}

This function takes an unsafe string as input and returns an escaped string by replacing all instances of HTML special characters with their escaped equivalents.

Escaping HTML Special Characters in Modern Browsers

For modern web browsers supporting the replaceAll method, you can use a simplified version of the escape function:

const escapeHtml = (unsafe) => {
  return unsafe
    .replaceAll("&amp;", "&amp;amp;")
    .replaceAll("<", "&amp;lt;")
    .replaceAll(">", "&amp;gt;")
    .replaceAll("&quot;", "&amp;quot;")
    .replaceAll("'", "&amp;#039;");
};

By using these functions, you can safely display HTML special characters in your JavaScript functions, ensuring that your content renders correctly and without any security issues.

The above is the detailed content of How Do I 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