4

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

Tim
  • 6,986
  • 8
  • 38
  • 57

2 Answers2

5

Try this:

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

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

Mārtiņš Briedis
  • 17,396
  • 5
  • 54
  • 76
  • The jQuery developers had us in mind; No need to do all that nasty HTML sanitation ourselves. :-) – Jake Mar 07 '11 at 20:57
  • Sorry I should have mentioned, I want SOME html, like bold tags to actually work... – Tim Mar 07 '11 at 21:21
0

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)

Brad Christie
  • 100,477
  • 16
  • 156
  • 200