我必须形成一个JSON字符串,其中一个值有新的行字符。这必须转义,然后使用AJAX调用发布。谁能建议一种用JavaScript转义字符串的方法?我没有使用jQuery。


当前回答

RegExp单行,使用这个函数:

function escapeJSON(string) {
    return string.replace(/[\n"\&\r\t\b\f]/g, '\\$&');
}

其他回答

获取JSON和.stringify()。然后使用.replace()方法将所有出现的\n替换为\\n。

编辑:

据我所知,没有知名的JS库用于转义字符串中的所有特殊字符。但是,你可以链接.replace()方法,像这样替换所有的特殊字符:

var myJSONString = JSON.stringify(myJSON);
var myEscapedJSONString = myJSONString.replace(/\\n/g, "\\n")
                                      .replace(/\\'/g, "\\'")
                                      .replace(/\\"/g, '\\"')
                                      .replace(/\\&/g, "\\&")
                                      .replace(/\\r/g, "\\r")
                                      .replace(/\\t/g, "\\t")
                                      .replace(/\\b/g, "\\b")
                                      .replace(/\\f/g, "\\f");
// myEscapedJSONString is now ready to be POST'ed to the server. 

但这很恶心,不是吗?函数的美妙之处在于,它们允许您将代码分解成片段,并保持脚本的主要流程干净,并且没有8个链式的.replace()调用。因此,让我们将该功能放入一个名为escapeSpecialChars()的函数中。让我们继续把它附加到String对象的原型链上,这样我们就可以直接在String对象上调用escapeSpecialChars()。

像这样:

String.prototype.escapeSpecialChars = function() {
    return this.replace(/\\n/g, "\\n")
               .replace(/\\'/g, "\\'")
               .replace(/\\"/g, '\\"')
               .replace(/\\&/g, "\\&")
               .replace(/\\r/g, "\\r")
               .replace(/\\t/g, "\\t")
               .replace(/\\b/g, "\\b")
               .replace(/\\f/g, "\\f");
};

一旦我们定义了这个函数,我们代码的主体就像这样简单:

var myJSONString = JSON.stringify(myJSON);
var myEscapedJSONString = myJSONString.escapeSpecialChars();
// myEscapedJSONString is now ready to be POST'ed to the server

EDIT: Check if the api you’re interacting with is set to Content-Type: application/json, &/or if your client http library is both stringify-ing and parsing the http request body behind the scenes. My client library was generated by swagger, and was the reason I needed to apply these hacks, as the client library was stringifying my pre-stringified body (body: “jsonString”, instead of body: { ...normal payload }). All I had to do was change the api to Content-Type: text/plain, which removed the JSON stringify/parsing on that route, and then none of these hacks were needed. You can also change only the "consumes" or "produces" portion of the api, see here.

原文:如果你的谷歌一直登陆你这里,你的api抛出错误,除非你的JSON双引号转义("{\"foo\": true}"),所有你需要做的是stringify两次,例如JSON.stringify(JSON.stringify(bar)))

RegExp单行,使用这个函数:

function escapeJSON(string) {
    return string.replace(/[\n"\&\r\t\b\f]/g, '\\$&');
}

这是一个旧帖子。但对于那些使用angular.fromJson和JSON.stringify的人来说,它仍然是有帮助的。 已弃用Escape()。 用这个代替,

var uri_enc = encodeURIComponent(uri); //before you post the contents
var uri_dec = decodeURIComponent(uri_enc); //before you display/use the contents.

ref http://www.w3schools.com/jsref/jsref_decodeuricomponent.asp

我使用内置的jQuery.serialize()从文本区域提取值以urlencode输入。专业的部分是,你不需要搜索替换每一个特殊的字符在你自己和我也保持换行符和转义html。为了序列化工作,似乎输入字段需要有一个name属性,但它也添加了相同的属性转义字符串,需要被替换掉。也许不是你想要的,但对我有用。

var myinputfield = jQuery("#myinputfield"); 
var text = myinputfield.serialize();
text = text.replace(myinputfield.attr('name') + '=','');