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
2009-05-11 15:06:04
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
2009-05-11 15:12:52
$(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
2009-05-11 15:31:27
$(ul selector).append('<li />').text(...) -- would this work instead or does append() return the parent instead of the created element?
Joe Philllips
2009-05-11 15:48:23
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
2009-05-11 16:43:48
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
2009-05-11 16:01:33
+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
2009-08-28 23:34:23