簡體   English   中英

JavaScript Regexp刪除JSON中轉義的反斜杠和引號

[英]JavaScript Regexp to remove escaped backslashes and quotation marks in JSON

根據我所讀的內容(例如, 本文 ),在將HTML作為JSON發送時,您需要轉義\\"

我想使用unescape() ,但是從JS 1.5開始不推薦使用。

w3schools建議:“ 改用解碼URI()或解碼URIComponent() ”。 但是decodeURI()decodeURIComponent()不會轉義\\"

我得到的響應看起來像:

"html": {
    "searchresult": "<div class=\\\"item\\\">\n\t\t\t<article class=\\\"unit\\\">\n\t\t\t\t<a href=\\\"page2.html\\\">Link<\\/a>\n\n\t\t\t\t\n\t\t\t<\\/article>\n\t\t<\\/div>"
}

然后,我將以下內容保存為var markup

return $('<textarea/>').html( response ).val();

最后剩下這個半工作的html

<div class=\"item\"> <article class=\"unit\"> <a href=\"page2.html\">Link<\/a> <\/article> <\/div>

我現在需要刪除所有\\之前" ,和/\\為它工作。猜猜除去在標簽之間的空白可能是一個獎金。

我嘗試了以下操作來刪除\\" ,效果很好。

markup.replace('\\"', '"');

但是我不知道如何刪除/\\ (加上.replace(blah).replace(blah)感覺不正確)。 本文給了我一個提示,但是我仍然對Regexp的魔術世界感到迷茫。

任何幫助,不勝感激!

您沒有說數據的來源,但我將假設您有一個有效的HTML字符串(顯然包含換行符和制表符),並且顯然您正在嘗試使的searchresult屬性為JSON中對象內部的html對象。 這樣做的方法如下:

var json = JSON.stringify({html: yourString});

例:

 var yourString = '<div class="item">\\n\\t\\t\\t<article class="unit">\\n\\t\\t\\t\\t<a href="page2.html">Link</a>\\n\\n\\t\\t\\t\\t\\n\\t\\t\\t</article>\\n\\t\\t</div>'; var json = JSON.stringify({html: yourString}); snippet.log("The JSON:"); snippet.log(json); 
 <!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 --> <script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script> 

如果要在整個字符串上將\\“更改為”。

markup.toString().replace(/\\"/g,'"');

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM