简体   繁体   中英

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM