正则表达式只删除两次出现的字符串

时间:2017-10-18 20:46:30

标签: javascript regex

我有以下字符串

"{\"title\": \"Option 1\", \"description\": \"This is the \"FIRST OPTION\" in the list.\"}"

我需要用&符号替换FIRST OPTION周围的转义引号;所以它看起来像这样:

"{\"title\": \"Option 1\", \"description\": \"This is the "FIRST OPTION" in the list.\"}"

我能想到的唯一方法是在 \“description \”:\“之后更改两次出现”:(它必须只有两个,因为在字符串末尾附近有转义引号需要保持这样)但我无法弄清楚语法(我对正则表达式来说很新)。

有没有办法用JS中的正则表达式实现这一点?

更新:忘记提及FIRST OPTION只是一个示例,它可以是任何字符串,我需要删除它周围的转义引号。

3 个答案:

答案 0 :(得分:0)

查找/\\"(?=FIRST OPTION)|(FIRST OPTION)\\"/
替换$1"

https://regex101.com/r/Nwnr13/2

或者,如果要求第一个选项同时包含两个转义引号,那么

查找/\\"(FIRST OPTION)\\"/
替换"$1"

https://regex101.com/r/tp9I5T/2

答案 1 :(得分:0)

参见此示例:



var text="{\"title\": \"Option 1\", \"description\": \"This is the \"FIRST OPTION\" in the list.\"}";
text=text.replace(/([\{|:|,])(?:[\s]*)(")/g, "$1'")
.replace(/(?:[\s]*)(?:")([\}|,|:])/g, "'$1")
.replace(/["]/gi, '"').replace(/[']/gi, '"');

text=JSON.stringify(text);
console.log(text);
  
text=JSON.parse(text);
console.log(text);




答案 2 :(得分:-1)

从您的JSON字符串开始,最简单的事情是理解,最安全的事情是将其重新转换为Javascript对象,仅对description字段进行操作,然后将其转换回字符串。
JSON.parse()和JSON.stringify()会这样做。
 (正如@jdubjdub所建议但没有写完,所以我去了)

你把它作为你的字符串:

"{\"title\": \"Option 1\", \"description\": \"This is the \"FIRST OPTION\" in the list.\"}"

要将其分配给变量用于我们的测试目的,需要额外的转义:

var yourstring = "{\"title\": \"Option 1\", \"description\": \"This is the \\\"FIRST OPTION\\\" in the list.\"}";

然后你会var obj = JSON.parse(yourstring)制作一个对象,只需obj.description进行操作即可替换引号,然后你var changedstring = JSON.stringify(obj)会再次使用字符串。< / p>

var yourstring = "{\"title\": \"Option 1\", \"description\": \"This is the \\\"FIRST OPTION\\\" in the list.\"}";
console.log('Original String:');
console.log(yourstring);

var obj = JSON.parse(yourstring);
console.log('String parsed into an Object:');
console.log(obj);

var newdesc = obj.description.replace(/"/g, '&quot;');
obj.description = newdesc;
console.log('Modified Object:');
console.log(obj);

var newstring = JSON.stringify(obj);
console.log('New String:');
console.log(newstring);

相关问题