print html tags in javascript

喜你入骨 提交于 2019-12-22 10:30:06

问题


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".

I tried:

str = str.replace("<", "");

but in vain.


回答1:


 data = data.replace(/</g, "&lt;").replace(/>/g, "&gt;");

When the browser encounters &lt; (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.

/</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.

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.




回答2:


The actual (and safer fix) is as follows:

function htmlspecialchars(text){
    return jQuery('<div/>').text(text).html();
}

In pure javascript, that would be:

function htmlspecialchars(text){
    var tnd=document.createTextNode(text);
    var div=document.createElement("DIV");
    div.appendChild(tnd);
    return div.innerHTML;
}



回答3:


It's ugly but you could try this (borrowed from Prototype's implementation of escapeHTML()):

var data = "<html> <head> <title> Hello </title> </head> <body> Hello Body </body> </html>"
    .replace(/&/g,'&amp;')
    .replace(/</g,'&lt;')
    .replace(/>/g,'&gt;');

document.write(data);

Of course creating a little helper function would be better.



来源:https://stackoverflow.com/questions/5627484/print-html-tags-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!