How would I sanitize this string? (preferably in JQuery)?
I have a webpage where p开发者_JS百科eople 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.
$('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.
If 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.
<input type="text" onkeyup="$('#outputDiv').text($(this).val());" />
<div id="outputDiv"></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()
精彩评论