JQuery HTML Preview Exception

I am making a very simple preview window in JQuery using only an ordered list. I'm worried that the user will enter <or> and accidentally mess up the code for the page or do something like XSS. How can I encode special characters using Javascript to handle this situation?

+1


a source to share


3 answers


if you use

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

      

then jQuery will render the actual text including special characters. If you are using



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

      

then HTML special characters will be interpreted when displayed.

I am assuming that you want to display the text that the user enters between the list tags.

+5


a source


You can also . wrap an element in <pre>

.



$("#selector").wrap("<pre></pre>");

      

+1


a source


If you want to store the escaped value in a variable and not display it on the page, you can also try:

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

      

+1


a source







All Articles