如何使用JavaScript转义包含换行符的JSON字符串?

2022-08-30 01:22:56

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


答案 1

获取您的 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个链式调用。因此,让我们将该功能放入一个名为 .让我们继续将其附加到对象的 ,这样我们就可以直接调用 String 对象。.replace()escapeSpecialChars()prototype chainStringescapeSpecialChars()

这样:

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

答案 2

根据 user667073 的建议,除了先重新排序反斜杠替换,并修复报价替换

escape = function (str) {
  return str
    .replace(/[\\]/g, '\\\\')
    .replace(/[\"]/g, '\\\"')
    .replace(/[\/]/g, '\\/')
    .replace(/[\b]/g, '\\b')
    .replace(/[\f]/g, '\\f')
    .replace(/[\n]/g, '\\n')
    .replace(/[\r]/g, '\\r')
    .replace(/[\t]/g, '\\t');
};