Run less / more than javascript
I have a problem trying to avoid some code ... Basically, I want to avoid "<" and ">", but I want them to APPEAR in my #output div as "<" and ">". They currently look like "& lt;" and & gt; On the page.
This is obviously to prevent anyone from using scripts on the page. This is my code:
var textval = $("#textarea").val(); //textarea filtered = textval.replace(/</gi,"<"); //replace "<" $("#output").html(filtered); //insert textarea data into div Can someone determine what I am doing wrong, or are there any better ways to do this?
Many thanks
EDIT: I need SOME html tags (e.g. <b> for work, so I can't use $ .text (), unfortunately ..)
Try the following:
var textval = $("#textarea").val(); $("#output").text(textval); jQuery offers two methods - $ .text () and $ .html (), where the method names speak for themselves :)
A bit different, but works for me (even with .html() ).
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 that this can be done, .text() is the best approach)