Home >Web Front-end >JS Tutorial >How Can I Escape HTML Special Characters in JavaScript Using Built-In or Custom Functions?

How Can I Escape HTML Special Characters in JavaScript Using Built-In or Custom Functions?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-19 04:31:02214browse

How Can I Escape HTML Special Characters in JavaScript Using Built-In or Custom Functions?

Escaping HTML Special Characters with JavaScript's Built-In 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.

Custom Implementation

One approach is to create a custom function that replaces specific characters:

function escapeHtml(text) {
  return text
      .replace(/&/g, "&")
      .replace(/</g, &quot;&amp;lt;&quot;)
      .replace(/>/g, &quot;&amp;gt;&quot;)
      .replace(/&quot;/g, &quot;&amp;quot;&quot;)
      .replace(/'/g, &quot;&amp;#039;&quot;);
}

This function iterates through the input text and replaces the special characters with their HTML-encoded equivalents.

Optimized Version

A performance-optimized version, suitable for extensive text processing:

function escapeHtml(text) {
  var map = {
    '&amp;': '&amp;amp;',
    '<': '&amp;lt;',
    '>': '&amp;gt;',
    '&quot;': '&amp;quot;',
    &quot;'&quot;: '&amp;#039;'
  };
  
  return text.replace(/[&amp;<>&quot;']/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!

Statement:
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