The core of the HTML entity decodement
The decodement of HTML entities is an essential foundational technology in the development of web pages.
Encoding
is a character that will have a special meaning (e.g.
<
,
>
,
&
) The process of converting it to its corresponding HTML physical code.
Decoding
is the process by which you restore these codes to original characters.
This mechanism ensures that characters are rendered as intended in browsers and are not deciphered as HTML Instruction. For example, if no code is performed, the browser will be
<script>
Parsing as a script label and trying to execute it instead of showing it as a plain text.
Encoding vs Decoding: Apply scene analysis
Data storage and transmission
HTML is usually required before user submissions (e.g. comments, comments) are posted to the database Encoding. This will not only prevent conflict of formats while stored, but also ensure that subsequent multiplatforms are followed (e.g., App, applet) is consistent when calling data.
2. Presentation of dynamic content
When you are moving to display data from untrustworthy sources on the page, you must decode or encode. If you want to show the source code, use the code; Use decode if you want to display a formatted version of the conversion.
Safety: Use code to prevent XSS attacks
Cross-Script Attack (XSS) is Web One of the most common loopholes in security. The attackers stole user information by injecting malicious foot on the page.
Conversion
It's the first line of defense for XSS. ♪ Pass by the will ♪
<
Convert to
<
, the attack script will be transformed into a harmless string, thus completely eliminating the risk of execution.
Common question: Why is there some character decoded or uncoded?
The problem of chaos is usually with
Character Encoding (Charset)
About. Although HTML entities provide a separate expression from the code, if your page states that
UTF-8
And the entity comes from
ISO-8859-1
Outside the scope and not correctly indicated, there may be an anomaly. Make sure you get it.
<meta charset="UTF-8">
Declares correct and gives priority to named HTML entities (e. g.
©
) not a number.
Decoding Scheme in JavaScript
In front-end development, you can decode in several ways:
-
DOM Method:
Use temporary creation
divElementalinnerTextortextContentattribute. This is the simplest and most compatible approach. -
Regular expression:
For specific core characters (e.g.,
&,<,>) Manually replaces. -
Modern API:
Use
DOMParserMore rigorous decode processing is also the option used in this tool.