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,954
  • 8
  • 54
  • 65
Haradzieniec
  • 9,086
  • 31
  • 117
  • 212

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
  • 5,533
  • 8
  • 35
  • 53
5

Something like this could work:

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

use this function that emulate the equivalent php function


Luca Filosofi
  • 30,905
  • 9
  • 70
  • 77