Home >Web Front-end >JS Tutorial >How Can I Decode HTML Entities in JavaScript and jQuery?

How Can I Decode HTML Entities in JavaScript and jQuery?

DDD
DDDOriginal
2024-12-16 04:17:10433browse

How Can I Decode HTML Entities in JavaScript and jQuery?

HTML Entity Decoding

To encode and decode HTML entities using JavaScript or jQuery, consider employing the following techniques:

Decode Entities Function

Create a specialized function to handle decoding, as seen below:

var decodeEntities = (function() {
  var element = document.createElement('div');

  function decodeHTMLEntities(str) {
    if (str && typeof str === 'string') {
      str = str
        .replace(/<script[^>]*>([\S\s]*?)<\/script>/gmi, '')
        .replace(/<\/?\w(?:[^"'>]|"[^"]*"|'[^']*')*>/gmi, '');
      element.innerHTML = str;
      str = element.textContent;
      element.textContent = '';
    }

    return str;
  }

  return decodeHTMLEntities;
})();

Using the Decode Entities Function

To use this function, simply call it with the encoded string:

var decodedString = decodeEntities("&amp;amp;");

jQuery Plugin Integration

You can integrate the decodeEntities function as a jQuery plugin by adding the following line:

jQuery.decodeEntities = decodeEntities;

This function effectively decodes HTML entities, removing overhead and sanitizing HTML tags in the input.

The above is the detailed content of How Can I Decode HTML Entities in JavaScript and jQuery?. 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