JavaScript Equivalent to PHP's htmlspecialchars
Determining if there is a JavaScript function equivalent to PHP's htmlspecialchars can be a challenge. However, an alternative approach is to define a custom function for this purpose.
Custom Function for HTML Character Escaping
While JavaScript does not provide a built-in function specifically for HTML character escaping, the following custom function can fulfill this need:
function escapeHtml(text) { return text .replace(/&/g, "&amp;") .replace(/</g, "&lt;") .replace(/>/g, "&gt;") .replace(/"/g, "&quot;") .replace(/'/g, "&#039;"); }
This function accepts a string as input and replaces the following special characters with their HTML character entity equivalents:
→ >
Performance Optimization
For improved performance, particularly with large text blocks, the following modified version of the function can be utilized:
function escapeHtml(text) { var map = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'"': '&#039;' }; return text.replace(/[&<>"']/g, function(m) { return map[m]; }); }
This version creates a hashtable (map) to map special characters to their corresponding entities, then uses the replace() method to perform the replacements.
The above is the detailed content of Is There a JavaScript Equivalent to PHP\'s `htmlspecialchars()`?. For more information, please follow other related articles on the PHP Chinese website!