返回

奇技淫巧:当你不得不 decode HTML Entity 字符串

前端

HTML Entity

HTML Entity 是一种将字符编码为可被 HTML 解析器识别的格式的方法。HTML Entity 使用 & 字符开始,后面跟着一个字符的名称或数字引用,再以 ; 字符结束。

例如,字符 “&” 的 HTML Entity 编码是 &amp;,字符 “<” 的 HTML Entity 编码是 &lt;,字符 “>” 的 HTML Entity 编码是 &gt;

解码 HTML Entity 字符串

在 JavaScript 中,可以使用内置的 decodeURI()decodeURIComponent() 方法来解码 HTML Entity 字符串。

decodeURI() 方法可以解码由 encodeURI() 方法编码的字符串。encodeURI() 方法会将所有非 ASCII 字符编码为 % 后跟两位十六进制数字的形式。

decodeURIComponent() 方法可以解码由 encodeURIComponent() 方法编码的字符串。encodeURIComponent() 方法会将所有非字母数字字符编码为 % 后跟两位十六进制数字的形式。

例如,以下代码使用 decodeURI() 方法解码一个由 encodeURI() 方法编码的字符串:

const encodedString = "http%3A%2F%2Fwww.example.com%2F";
const decodedString = decodeURI(encodedString);
console.log(decodedString); // 输出:http://www.example.com/

以下代码使用 decodeURIComponent() 方法解码一个由 encodeURIComponent() 方法编码的字符串:

const encodedString = "username%3Djohn%26password%3Dsecret";
const decodedString = decodeURIComponent(encodedString);
console.log(decodedString); // 输出:username=john&password=secret

常见的 HTML Entity 字符

下表列出了一些常见的 HTML Entity 字符和对应的编码值:

字符 HTML Entity 编码
& &amp;
< &lt;
> &gt;
" &quot;
' &apos;
© &copy;
® &reg;
&trade;
§ &sect;
&para;

结论

HTML Entity 是一种将字符编码为可被 HTML 解析器识别的格式的方法。在 JavaScript 中,可以使用内置的 decodeURI()decodeURIComponent() 方法来解码 HTML Entity 字符串。