Is there a native way to encode or decode HTML entities using JavaScript or ES6? For example, <
would be encoded as <
. There are libraries like html-entities
for Node.js but it feels like there should be something built into JavaScript that already handles this common need.
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- void before promise syntax
- npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fs
- Keeping track of variable instances
To
unescape
HTML entities, Your browser is smart and will do it for youWay1
Way2
You can also use underscore or lodash's unescape method but this ignores
and handles only&
,<
,>
,"
, and'
characters.There is no native function in the JavaScript API that convert ASCII characters to their "html-entities" equivalent. Here is a beginning of a solution and an easy trick that you may like
Roll Your Own (caveat - use HE instead for most use cases)
For pure JS without a lib, you can Encode and Decode HTML entities using pure Javascript like this:
Usages:
However, you can see this approach has a couple shortcomings:
H
→H
>
Use the HE Library (Html Entities)
Usage:
A nice function using es6 for escaping html: