How would I sanitize this string? (preferably in JQuery)?

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.

1

4 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.

0

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.

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() 

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like