Mar*_*ang 14 javascript html-entities node.js
是否有使用JavaScript或ES6 编码或解码HTML实体的本机方法?例如,<将被编码为<.有像html-entitiesNode.js这样的库,但感觉应该有一些内置于JavaScript中的东西已经处理了这个常见的需求.
asa*_*fel 19
使用 es6 转义 html 的一个不错的函数:
const escapeHTML = str => str.replace(/[&<>'"]/g,
tag => ({
'&': '&',
'<': '<',
'>': '>',
"'": ''',
'"': '"'
}[tag]));
Run Code Online (Sandbox Code Playgroud)
对于没有 lib 的纯 JS,您可以使用纯 Javascript 对 HTML 实体进行编码和解码如下所示:
\n\nlet encode = str => {\n let buf = [];\n\n for (var i = str.length - 1; i >= 0; i--) {\n buf.unshift([\'&#\', str[i].charCodeAt(), \';\'].join(\'\'));\n }\n\n return buf.join(\'\');\n}\n\nlet decode = str => {\n return str.replace(/&#(\\d+);/g, function(match, dec) {\n return String.fromCharCode(dec);\n });\n}\nRun Code Online (Sandbox Code Playgroud)\n\n用法:
\n\nencode("Hello > \xc2\xa9 <") // "Hello > © <"\ndecode("Hello > © © <") // "Hello > © \xc2\xa9 <"\nRun Code Online (Sandbox Code Playgroud)\n\n然而,您可以看到这种方法有一些缺点:
\n\nH\xe2\x86\x92进行编码H>用法:
\n\nhe.encode(\'foo \xc2\xa9 bar \xe2\x89\xa0 baz qux\'); \n// Output : \'foo © bar ≠ baz 𝌆 qux\'\n\nhe.decode(\'foo © bar ≠ baz 𝌆 qux\');\n// Output : \'foo \xc2\xa9 bar \xe2\x89\xa0 baz qux\'\nRun Code Online (Sandbox Code Playgroud)\n\n| 归档时间: |
|
| 查看次数: |
13545 次 |
| 最近记录: |