jQuery Escaping HTML from a Textarea

我们两清 提交于 2019-12-22 04:46:12

问题


I want to escape HTML tags to entity names, taking text from a textarea and putting the result in a second textarea such that:

<mytag>

becomes

&lt;mytag&gt;

I'm using .html() and .text() going back and forth OK. My problem is dealing with the textarea element, which acts a little different.

It works fine if I first place the text into a div:

var htmlStr = $('#textareaInput').val(); //doesn't like .html() .text() ?
$('#dummy').text(htmlStr); // an object to hold the text that supports .html() 
$('#textareaOutput').val($('#dummy').html());

But I want to do something more straightforward like this:

var htmlStr = $('#textareaInput').val(); 
$('#textareaOutput').val($(htmlStr).html());

I guess my problem is that I don't understand how to manipulate jQuery objects, like strings, without manipulating DOM elements -because right now I'm using a div because it has the .html() method.

Any help would be fantastic!

Thanks.


回答1:


try

var htmlStr = $('#textareaInput').val(); 
$('#textareaOutput').val($('<div/>').text(htmlStr).html());


来源:https://stackoverflow.com/questions/3353129/jquery-escaping-html-from-a-textarea

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!