13

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.

Cœur
  • 37,241
  • 25
  • 195
  • 267
TIMEX
  • 259,804
  • 351
  • 777
  • 1,080
  • then use `var txt = $('div').text();` Read https://stackoverflow.com/questions/1910794/what-is-the-difference-between-jquery-text-and-html – csandreas1 Jan 30 '19 at 08:20

4 Answers4

18
$('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.

David Fells
  • 6,678
  • 1
  • 22
  • 34
1

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.

icktoofay
  • 126,289
  • 21
  • 250
  • 231
1
<input type="text" onkeyup="$('#outputDiv').text($(this).val());" />
<div id="outputDiv"></div>
bloodcell
  • 601
  • 1
  • 9
  • 23
0

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() 
Adam Prax
  • 6,413
  • 3
  • 30
  • 31