views:

687

answers:

3

I am making a very simple preview window in JQuery using just an ordered list. I am worried the user will type in < or > and accidentally mess up the code for the page or do some sort of XSS. How can I encode special chars using Javascript to handle this situation?

+5  A: 

if you use

$(yourselector).text("<h1>Your text String</h1>");

then jQuery will display the actual text including the special chars. If you use

$(yourselector).html("<h1>Your text String</h1>");

then the HTML special chars will be interpreted when displayed.

I assume here that you want to display the text that your user enters between the list tags.

Vincent Ramdhanie
In my case I'm making a list so I currently have something like this:$(selector).html('<li>' + $(this).val() + '</li>') -- how would I convert this to your method?
Joe Philllips
$(Your UL selector).append('<li id="someid"></li>'); adds the li to the list and $("#someid").text($(this).val()); will then add the text to the new li. You will need to use a variable as the li's id.
Vincent Ramdhanie
$(ul selector).append('<li />').text(...) -- would this work instead or does append() return the parent instead of the created element?
Joe Philllips
append() returns the parent so as far as I can tell you need use the two statements. I don't know if anyone else could suggest a way to do it all in one statement.
Vincent Ramdhanie
+1  A: 

You could also .wrap the element in a <pre> tag.

$("#selector").wrap("<pre></pre>");
tester
This might not the best idea for XSS prevention though, now that I think about it. Someone could start the input off with </pre> and end it with <pre> then inject whatever code they wanted in the center. Converting to .text() is more than likely the best solution.
tester
+1  A: 

If you want to store the escaped value in a variable, rather than rendering it to the page, you could also try:

$('<div></div>').text(str).html()
Brian Westphal