簡體   English   中英

Javascript:不能用一個雙引號替換兩個雙引號

[英]Javascript: cannot replace two double quotes with a single doublequote

value "//a[@class="post-tag"]" ,我試圖從返回""//a[@class=\\"post-tag\\"]""jsonString刪除兩個雙引號""//a[@class=\\"post-tag\\"]""

                            var jsonString = JSON.stringify(value);
                            var cleanjson = jsonString.replace(/""/g, '"');

我不明白為什么這個簡單的例子不起作用。 jsonString返回""//a[@class=\\"post-tag\\"]""我試圖用一個雙引號替換兩個雙引號。 但是, cleanjson仍然會有兩個雙引號。

您無法刪除兩個雙引號,因為它們不存在於您的變量中

jsonString變量的值是"//a[@class="post-tag"]" ,但是因為是字符串,所以會用雙引號封裝起來顯示: ""//a[@class="post-tag"]""

在字符串化之前修剪外部引號可能更簡單:

 var value = '"//a[@class="post-tag"]"'; // Remove quotes at the beginning and end var trimmed = value.replace(/(^"|"$)/g, ''); console.log(trimmed); // -> //a[@class="post-tag"] // Escape remaining quotes and add outer quotes back var escaped = JSON.stringify(trimmed); console.log(escaped); // -> "//a[@class=\\"post-tag\\"]"

暫無
暫無

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

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