I have a <textarea id="mytextarea"></textarea>
.
Let's say a user typed in there: <hello>, world!
How to get res = "<hello>, 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.
I have a <textarea id="mytextarea"></textarea>
.
Let's say a user typed in there: <hello>, world!
How to get res = "<hello>, 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.
Share Improve this question edited Apr 26, 2014 at 9:32 Emissary 10.1k9 gold badges56 silver badges67 bronze badges asked Apr 23, 2014 at 18:16 HaradzieniecHaradzieniec 9,34833 gold badges122 silver badges227 bronze badges 4- 1 possible duplicate of Can I escape html special chars in javascript? – Kevin B Commented Apr 23, 2014 at 18:23
- @Haradzieniec: i have added a working demo... – Luca Filosofi Commented Apr 23, 2014 at 18:49
- Why it is duplicate, if it is not. I saw that question you've mentioned before I asked. I was curious if it is possible to do WITH jQuery. – Haradzieniec Commented Apr 23, 2014 at 18:50
- And I answered straight away with the solution.. – ptimson Commented Apr 23, 2014 at 18:51
3 Answers
Reset to default 5Already answered: Can I escape html special chars in javascript?
function escapeHtml(unsafe) {
return unsafe
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}
var res = escapeHtml($('#mytextarea').val());
Something like this could work:
var res = $("<div/>").text($('#mytextarea').val()).html();
- demo : http://so.devilmaycode.it/get-html-escaped-text-from-textarea-with-jquery/
use this function that emulate the equivalent php function
- http://phpjs/functions/htmlentities/
- http://phpjs/functions/get_html_translation_table/
- http://php/manual/en/function.htmlentities.php