转义html
var entityMap = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": ''',
'/': '/',
'`': '`',
'=': '='
};
function escapeHtml (string) {
return String(string).replace(/[&<>"'`=\/]/g, function (s) {
return entityMap[s];
});
}
转义字符转换成普通字符
var entityMap2 = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
''': "'",
'/': '/',
'`': '`',
'=': '='
};
function unescapeHtml (string) {
return String(string).replace(/&(amp|lt|gt|quot|#39|#x2F|#x60|#x3D);/ig, function (s) {
return entityMap2[s];
});
}
删除html标签
function removeHtmlTag(content) {
return content.replace(/<[^<>]+?>/g,'');
}
示例
var content = "<div><p> text </p></div>";
var escapeContent = escapeHtml(content);
console.log("escapeContent: " + escapeContent);
var unescapteContent = unescapeHtml(escapeContent);
console.log(unescapteContent);
var text = removeHtmlTag(content);
console.log(text);
输出结果为:
escapeContent: <div><p> text </p></div>
unescapteContent: <div><p> text </p></div>
text: text