Home > Article > Web Front-end > How to Effectively Escape HTML Special Characters in JavaScript?
JavaScript Equivalent of PHP's HtmlSpecialChars
In PHP, the htmlspecialchars function is used to encode special characters, such as <, >, and &, into HTML entities. For example, < becomes <.
JavaScript does not have a built-in function that exactly replicates the behavior of htmlspecialchars. The closest equivalent is to use a custom function that performs the following steps:
One possible implementation of such a function is:
function escapeHtml(text) { return text .replace(/&/g, "&amp;") .replace(/</g, "&lt;") .replace(/>/g, "&gt;") .replace(/"/g, "&quot;") .replace(/'/g, "&#039;"); }
This function will escape all occurrences of the specified special characters. However, it is important to note that it does not escape all possible special characters. For example, it does not escape the ' ' character, which can be used to represent spaces in URLs.
For better performance, especially with large text blocks, you can use a lookup table approach:
function escapeHtml(text) { var map = { '&': '&', '<': '<', '>': '>', '"': '"', "'": '&#039;' }; return text.replace(/[&<>"']/g, function(m) { return map[m]; }); }
This approach reduces the amount of string manipulation required, resulting in improved performance.
The above is the detailed content of How to Effectively Escape HTML Special Characters in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!