Tim
Tim

Reputation: 7056

escape less / greater than javascript

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

Upvotes: 4

Views: 6420

Answers (2)

Brad Christie
Brad Christie

Reputation: 101614

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)

Upvotes: 0

Mārtiņš Briedis
Mārtiņš Briedis

Reputation: 17762

Try this:

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

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

Upvotes: 5

Related Questions