Home >Web Front-end >JS Tutorial >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(/&/g, "&amp;") .replace(/</g, "&lt;") .replace(/>/g, "&gt;") .replace(/"/g, "&quot;") .replace(/'/g, "&#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;") .replaceAll("<", "&lt;") .replaceAll(">", "&gt;") .replaceAll(""", "&quot;") .replaceAll("'", "&#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!