最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Get html-escaped text from textarea with jQuery - Stack Overflow

programmeradmin4浏览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.

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.

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
Add a ment  | 

3 Answers 3

Reset to default 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());

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
发布评论

评论列表(0)

  1. 暂无评论