0

I have a <textarea id="mytextarea"></textarea>.

Let's say a user typed in there: <hello>, world!

How to get res = "&lt;hello&gt;, world!"; from what user typed?

This code doesn't work:

var res = $('#mytextarea').val().html();

It says:

Uncaught TypeError: undefined is not a function 

P.S. var res = $('#mytextarea').val(); works just fine, but I need the text from the textarea became html-escaped.

How to do it with jQuery?

Thank you.

Emissary
  • 9,520
  • 8
  • 53
  • 60
Haradzieniec
  • 8,592
  • 29
  • 109
  • 204

3 Answers3

5

Already answered: Can I escape html special chars in javascript?

function escapeHtml(unsafe) {
    return unsafe
         .replace(/&/g, "&amp;")
         .replace(/</g, "&lt;")
         .replace(/>/g, "&gt;")
         .replace(/"/g, "&quot;")
         .replace(/'/g, "&#039;");
}

var res = escapeHtml($('#mytextarea').val());
Community
  • 1
  • 1
ptimson
  • 4,923
  • 8
  • 34
  • 52
5

Something like this could work:

var res = $("<div/>").text($('#mytextarea').val()).html();
keune
  • 5,701
  • 4
  • 32
  • 49
-1

use this function that emulate the equivalent php function


Luca Filosofi
  • 30,511
  • 8
  • 67
  • 75