javascript 在javascript中打印html标签
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5627484/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
print html tags in javascript
提问by Sagar Hatekar
Thanks for reading!
谢谢阅读!
var data = "<html><head><title>Hello</title></head><body>Hello Body</body></html>";
I want to print data
including the HTML tags without having the browser rendering the HTML tags and just displaying "Hello Body".
我想打印data
包括 HTML 标签,而无需浏览器呈现 HTML 标签并只显示“Hello Body”。
I tried:
我试过:
str = str.replace("<", "");
str = str.replace("<", "");
but in vain.
但徒劳无功。
回答by Matt Greer
data = data.replace(/</g, "<").replace(/>/g, ">");
When the browser encounters <
(which is known as a character entity), it will replace it with a literal '<', enabling you to display the HTML tags on the page without them getting rendered.
当浏览器遇到<
(称为字符实体)时,它将用文字“<”替换它,使您能够在页面上显示 HTML 标签而不会被渲染。
/</g
is a regular expression that just says "match all '<' in the string", and g
means do it globally. Without the g
it will only replace the first '<' it encounters.
/</g
是一个正则表达式,它只是说“匹配字符串中的所有 '<'”,g
意思是全局执行。如果没有g
它,它只会替换它遇到的第一个 '<'。
And one final note, it's much better to use a library, such as jQuery, to do this. This is the kind of stuff that is easy to get wrong and miss edge cases on. Let the hardened, well tested and secure library function do it for you.
最后要注意的是,最好使用诸如 jQuery 之类的库来执行此操作。这是一种很容易出错和错过边缘情况的东西。让强化的、经过良好测试的和安全的库函数为您完成。
回答by Christian
The actual (and safer fix) is as follows:
实际(和更安全的修复)如下:
function htmlspecialchars(text){
return jQuery('<div/>').text(text).html();
}
In pure javascript, that would be:
在纯 javascript 中,这将是:
function htmlspecialchars(text){
var tnd=document.createTextNode(text);
var div=document.createElement("DIV");
div.appendChild(tnd);
return div.innerHTML;
}
回答by C???
It's ugly but you could try this (borrowed from Prototype's implementation of escapeHTML()
):
这很难看,但你可以试试这个(从 Prototype 的实现中借来的escapeHTML()
):
var data = "<html> <head> <title> Hello </title> </head> <body> Hello Body </body> </html>"
.replace(/&/g,'&')
.replace(/</g,'<')
.replace(/>/g,'>');
document.write(data);
Of course creating a little helper function would be better.
当然,创建一个小辅助函数会更好。