javascript 如何使用jQuery从textarea中转义特殊字符?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12409314/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 16:07:15  来源:igfitidea点击:

How to escape special characters from textarea using jQuery?

javascriptjqueryhtmljquery-plugins

提问by user1595858

I want to know if there are any jquery components which automatically take care of special characters. This basically means converting &to &ampand also all listed in here, so that when I send data to the backend it stores in that format. And then while retrieving we need to convert it back from &ampto &.

我想知道是否有任何 jquery 组件可以自动处理特殊字符。这基本上意味着转换&&amp并全部列在此处,以便当我将数据发送到后端时,它会以该格式存储。然后一边检索,我们需要将其转换回从&amp&

We will be using a lot of mathematical symbols so we need a functionality in JavaScript which does that. Also I have seen a rich text editor but we don't need lot of its features such as images, paragraph etc, though we want the text editor to have some icon or something to insert mathematics symbols and source code. In a nutshell, I'm looking something like the Stackoverflow editor, without images.

我们将使用大量数学符号,因此我们需要 JavaScript 中的一个功能来实现这一点。我也见过富文本编辑器,但我们不需要它的很多功能,如图像、段落等,尽管我们希望文本编辑器有一些图标或其他东西来插入数学符号和源​​代码。简而言之,我看起来像 Stackoverflow 编辑器,没有图像。

回答by Ryan

You can use jQuery to do this for you:

您可以使用 jQuery 为您执行此操作:

function htmlEncode(value){
    if (value) {
        return jQuery('<div />').text(value).html();
    } else {
        return '';
    }
}

function htmlDecode(value) {
    if (value) {
        return $('<div />').html(value).text();
    } else {
        return '';
    }
}


$(document).ready(function() {
    alert( htmlEncode ("this is a & test") );
});

Code originally from http://www.naveen.com.au/javascript/jquery/encode-or-decode-html-entities-with-jquery/289.?

代码最初来自http://www.naveen.com.au/javascript/jquery/encode-or-decode-html-entities-with-jquery/289.?

回答by Jeremy J Starcher

You didn't say how you were submitting things, but chances are encodeURIComponentwill be your friend.

你没有说你是如何提交东西的,但encodeURIComponent很有可能是你的朋友。

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/encodeURIComponent

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/encodeURIComponent

The link was down when I posted, but Mozilla should be up and running soon.

我发布时链接已关闭,但 Mozilla 应该很快就会启动并运行。

回答by Hictus

The function encodeURIComponent($('#textarea').val())will solve your problem.

该功能encodeURIComponent($('#textarea').val())将解决您的问题。