最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - escape lessgreater than javascript - Stack Overflow

programmeradmin7浏览0评论

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

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

Share Improve this question edited Mar 7, 2011 at 21:22 Tim asked Mar 7, 2011 at 20:51 TimTim 7,0568 gold badges40 silver badges57 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

Try this:

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

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

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)

发布评论

评论列表(0)

  1. 暂无评论