是否存在使用JavaScript或ES6编码或解码HTML entities的本机方式?例如,<
将被编码为<
。 Node.js有像html-entities
这样的库,但感觉应该有一些内置于JavaScript中的东西已经处理了这个常见的需求。
答案 0 :(得分:3)
JavaScript API中没有将ASCII字符转换为其“html-entities”等效字符的本机函数。 这是您可能想要的beginning of a solution和easy trick
答案 1 :(得分:1)
使用es6来转义html的不错功能:
const escapeHTML = str => str.replace(/[&<>'"]/g,
tag => ({
'&': '&',
'<': '<',
'>': '>',
"'": ''',
'"': '"'
}[tag] || tag));
答案 2 :(得分:0)
对于不带库的纯JS,您可以这样Encode and Decode HTML entities using pure Javascript:
let encode = str => {
let buf = [];
for (var i = str.length - 1; i >= 0; i--) {
buf.unshift(['&#', str[i].charCodeAt(), ';'].join(''));
}
return buf.join('');
}
let decode = str => {
return str.replace(/&#(\d+);/g, function(match, dec) {
return String.fromCharCode(dec);
});
}
用法:
encode("Hello > © <") // "Hello > © <"
decode("Hello > © © <") // "Hello > © © <"
但是,您可以看到这种方法有一些缺点:
H
→H
>
用法:
he.encode('foo © bar ≠ baz ? qux');
// Output : 'foo © bar ≠ baz 𝌆 qux'
he.decode('foo © bar ≠ baz 𝌆 qux');
// Output : 'foo © bar ≠ baz ? qux'
答案 3 :(得分:0)
对于unescape
HTML实体,您的浏览器很聪明,将为您做到
方法1
_unescape(html: string) :string {
const divElement = document.createElement("div");
divElement.innerHTML = html;
return divElement.textContent || tmp.innerText || "";
}
方法2
_unescape(html: string) :string {
let returnText = html;
returnText = returnText.replace(/ /gi, " ");
returnText = returnText.replace(/&/gi, "&");
returnText = returnText.replace(/"/gi, `"`);
returnText = returnText.replace(/</gi, "<");
returnText = returnText.replace(/>/gi, ">");
return returnText;
}
您还可以使用underscore或lodash的unescape方法,但这会忽略
并仅处理&
,<
,>
,"
和'
个字符。