Home >Web Front-end >JS Tutorial >How Can I Escape HTML Special Characters in JavaScript Using Built-In or Custom Functions?
As the inquiry suggests, PHP's htmlspecialchars provides a convenient way to encode HTML special characters upon translation. A corresponding function in JavaScript would significantly simplify the task.
While built-in functions like escape() and encodeURI() do not handle character escaping as expected, there are alternatives available.
One approach is to create a custom function that replaces specific characters:
function escapeHtml(text) { return text .replace(/&/g, "&amp;") .replace(/</g, "&lt;") .replace(/>/g, "&gt;") .replace(/"/g, "&quot;") .replace(/'/g, "&#039;"); }
This function iterates through the input text and replaces the special characters with their HTML-encoded equivalents.
A performance-optimized version, suitable for extensive text processing:
function escapeHtml(text) { var map = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#039;' }; return text.replace(/[&<>"']/g, function(m) { return map[m]; }); }
This implementation uses a JavaScript object to map special characters to their escape sequences, leveraging the fast replacement performance of regular expressions.
The above is the detailed content of How Can I Escape HTML Special Characters in JavaScript Using Built-In or Custom Functions?. For more information, please follow other related articles on the PHP Chinese website!