Home > Web Front-end > JS Tutorial > Is There a JavaScript Equivalent to PHP\'s `htmlspecialchars()`?

Is There a JavaScript Equivalent to PHP\'s `htmlspecialchars()`?

DDD
Release: 2024-11-17 18:54:02
Original
224 people have browsed it

Is There a JavaScript Equivalent to PHP's `htmlspecialchars()`?

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, "&")
      .replace(/</g, "&amp;lt;")
      .replace(/>/g, "&amp;gt;")
      .replace(/&quot;/g, "&amp;quot;")
      .replace(/'/g, "&amp;#039;");
}
Copy after login

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;': '&amp;amp;',
    '<': '&amp;lt;',
    '>': '&amp;gt;',
    '&quot;': '&amp;quot;',
    "'"': '&amp;#039;'
  };
  
  return text.replace(/[&amp;<>&quot;']/g, function(m) { return map[m]; });
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template