感谢您的阅读!
var data = "<html><head><title>Hello</title></head><body>Hello Body</body></html>";
我想打印
data
包括 HTML 标签,而不让浏览器渲染 HTML 标签并只显示“Hello Body”。
我尝试过:
str = str.replace("<", "");
但是徒劳无功。
data = data.replace(/</g, "<").replace(/>/g, ">");
当浏览器遇到
<
(称为字符实体)时,它会将其替换为文字 '<', enabling you to display the HTML tags on the page without them getting rendered.
/</g
是一个正则表达式,只是说“匹配所有 '<' in the string", and g
意味着在全局范围内执行。如果没有 g
,它只会替换第一个 '<' it encounters.
最后一点,最好使用库(例如 jQuery)来执行此操作。这是一种很容易出错并错过边缘情况的东西。让经过强化、经过充分测试且安全的库函数为您做这件事。
实际(也是更安全的修复)如下:
function htmlspecialchars(text){
return jQuery('<div/>').text(text).html();
}
在纯 JavaScript 中,这将是:
function htmlspecialchars(text){
var tnd=document.createTextNode(text);
var div=document.createElement("DIV");
div.appendChild(tnd);
return div.innerHTML;
}
它很难看,但你可以尝试这个(借用 Prototype 的
escapeHTML()
实现):
var data = "<html> <head> <title> Hello </title> </head> <body> Hello Body </body> </html>"
.replace(/&/g,'&')
.replace(/</g,'<')
.replace(/>/g,'>');
document.write(data);
当然创建一个小辅助函数会更好。