在javascript中打印html标签 [英] print html tags in javascript

查看:101
本文介绍了在javascript中打印html标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



  var data =< html>< head>< title> Hello< title>< / head>< body> Hello Body< / body>< / html>; 

我想打印 data ,包括HTML标签没有浏览器呈现HTML标签,只显示你好身体。



我试过了:

$ b $ str = str.replace( <,);



但徒然。

解决方案 div>

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

当浏览器遇到& lt; (它被称为字符实体),它将用一个文字'<'替换它,使您能够在页面上显示HTML标签而不会渲染它们。



/< / g 是一个正则表达式,只表示字符串中的匹配所有<' , g 意味着全球化。没有 g 它只会替换遇到的第一个'<'。

最后要说明的是,使用库(如jQuery)来做到这一点更好。这是一种容易出错并错过边缘案例的东西。让硬化,经过充分测试和安全的库函数为你做。


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.

解决方案

 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.

这篇关于在javascript中打印html标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆