简体   繁体   English

使用jQuery从textarea获取html转义的文本

[英]Get html-escaped text from textarea with jQuery

I have a <textarea id="mytextarea"></textarea> . 我有一个<textarea id="mytextarea"></textarea>

Let's say a user typed in there: <hello>, world! 假设有一个用户在这里输入: <hello>, world!

How to get res = "&lt;hello&gt;, world!"; 如何获得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 

PS var res = $('#mytextarea').val(); PS var res = $('#mytextarea').val(); works just fine, but I need the text from the textarea became html-escaped. 工作正常,但我需要将textarea中的文本转为html转义。

How to do it with jQuery? 如何使用jQuery?

Thank you. 谢谢。

Already answered: Can I escape html special chars in javascript? 已经回答: 我可以在javascript中转义html特殊字符吗?

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());

这样的事情可能会起作用:

var res = $("<div/>").text($('#mytextarea').val()).html();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM