escape less / greater than javascript

和自甴很熟 提交于 2019-12-19 08:59:41

问题


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 "&lt;" and "&gt;" 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,"&lt;");           //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..)


回答1:


Try this:

var textval = $("#textarea").val();
$("#output").text(textval);      

jQuery offers two methods - $.text() and $.html() where the method names speak for themselves :)




回答2:


A little different replace, but works for me (even with .html()).

Demo

var str = $('#textarea').val();
$('#result').html(str.replace(/<|>/ig,function(m){
    return '&'+(m=='>'?'g':'l')+'t;';
}));

<textarea id="textarea">
    Hello, <b>World</b>!
</textarea>
<div id="result"></div>

(This is just to verify it can be done, .text() is the better approach)



来源:https://stackoverflow.com/questions/5225096/escape-less-greater-than-javascript

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