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
Release: 2024-12-16 04:17:10
Original
432 people have browsed it

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;
})();
Copy after login

Using the Decode Entities Function

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

var decodedString = decodeEntities("&amp;amp;");
Copy after login

jQuery Plugin Integration

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

jQuery.decodeEntities = decodeEntities;
Copy after login

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!

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