且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-11-13 22:54:22

获取JSON和 .stringify()它。然后使用 .replace()方法,并将所有出现的 \\\
\\ \\

Take your JSON and .stringify() it. Then use the .replace() method and replace all occurrences of \n with \\n.

编辑:

据我所知,没有知名的JS库可以全部转义字符串中的特殊字符。但是,您可以链接 .replace()方法,并替换所有特殊字符,如下所示:

As far as I know of, there are no well-known JS libraries for escaping all special characters in a string. But, you could chain the .replace() method and replace all of the special characters like this:

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 对象的原型链中,因此我们可以调用 escapeSpecialChars()直接在String对象上。

But that's pretty nasty, isn't it? Enter the beauty of functions, in that they allow you to break code into pieces and keep the main flow of your script clean, and free of 8 chained .replace() calls. So let's put that functionality into a function called, escapeSpecialChars(). Let's go ahead and attach it to the prototype chain of the String object, so we can call escapeSpecialChars() directly on String objects.

像这样:

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");
};

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

Once we have defined that function, the main body of our code is as simple as this:

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