I have a webpage where people type stuff into a text box, and it displays that text below them. That's it. There is no server side.
Let's say someone types <script src="blah">hello</script>
I want to display that as text. Not as a script, of course. How can I do that (all in javascript)?
I want to display the entire text. Don't stip the tags out.
14 Answers
$('div.whatever').text($('input.whatever').val()); That'll convert things to HTML entities, so they're displayed as they were typed, and not treated as markup.
0If you want to display it in an element, you can use the text method. It will escape all the HTML for you.
You can see an example here.
1<input type="text" onkeyup="$('#outputDiv').text($(this).val());" /> <div></div> A quick way to sanitize any string in general with JQuery would be create a temporary element, set the text content with the text method and then retrieve the escaped text with text again.
const unsanitized = '<script>alert()></script>' // Outputs '<\script>alert()><\/script>' const sanitized = $("<p>").text(unsanitized).text()