Home > Web Front-end > JS Tutorial > How to Encode and Decode HTML Entities in JavaScript?

How to Encode and Decode HTML Entities in JavaScript?

DDD
Release: 2024-12-11 19:14:11
Original
220 people have browsed it

How to Encode and Decode HTML Entities in JavaScript?

HTML Entity Decoding

HTML entities are characters represented using their hexadecimal codepoints preceded by an ampersand (&) and a semicolon (;). For example, the ampersand character (&) is represented as &.

Encoding HTML Entities in JavaScript

To encode an HTML entity in JavaScript, use the encodeURIComponent() function. This function takes a string as input and returns a new string with all non-ASCII characters encoded as HTML entities. For instance, the following code encodes the ampersand character (&) as &:

encodeURIComponent('&'); // "&"
Copy after login

Decoding HTML Entities in JavaScript with jQuery

To decode an HTML entity in JavaScript using jQuery, use the html() function. This function takes a string as input and returns a new string with all HTML entities decoded. For example, the following code decodes the string "&" into the ampersand character (&):

$.html('&'); // "&"
Copy after login

Decoding HTML Entities in JavaScript without jQuery

If you do not want to use jQuery, you can use the following custom function to decode HTML entities in JavaScript:

function decodeEntities(string) {
  var doc = new DOMParser().parseFromString(string, "text/html");
  return doc.documentElement.textContent;
}
Copy after login

This function creates a new DOM element from the input string and then extracts the text content from the DOM element, which will have all HTML entities decoded. For example, the following code decodes the string "&" into the ampersand character (&):

decodeEntities('&'); // "&"
Copy after login

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