转义小于/大于 javascript
我在尝试转义某些代码时遇到问题...基本上,我想转义“<”和“>”但我希望它们在我的#output div 中显示为“<”和“>”。目前,它们显示为“<”和“>”在页面上。
这显然是为了防止任何人在页面上利用/注入脚本。这是我的代码:
var textval = $("#textarea").val(); //textarea
filtered = textval.replace(/</gi,"<"); //replace "<"
$("#output").html(filtered); //insert textarea data into div
任何人都可以发现我做错了什么,或者有更好的方法吗?
非常感谢
编辑:我确实想要一些 html 标签(比如 工作,所以我不能使用 $.text(); 不幸的是..)
I'm having a problem trying to escape some code... Basically, I want to escape "<" and ">" but I want them to APPEAR in my #output div as "<" and ">". Currently, they appear as as "<" and ">" on the page.
This is obviously to prevent anyone exploiting / injecting scripts on the page. This is my code:
var textval = $("#textarea").val(); //textarea
filtered = textval.replace(/</gi,"<"); //replace "<"
$("#output").html(filtered); //insert textarea data into div
Can anybody spot what I am doing wrong, or are there any better ways of doing this?
Many thanks
EDIT: I do want SOME html tags (like <b> to work, so I can't use $.text(); unfortunately..)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
试试这个:
jQuery 提供了两种方法 - $.text() 和 $.html(),其中方法名称不言自明:)
Try this:
jQuery offers two methods - $.text() and $.html() where the method names speak for themselves :)
有点不同的替换,但对我有用(即使使用
.html()
)。演示
(这只是为了验证它是否可以完成,
.text()
是更好的方法)A little different replace, but works for me (even with
.html()
).Demo
(This is just to verify it can be done,
.text()
is the better approach)