在javascript中替换方法

时间:2014-01-30 17:16:12

标签: javascript regex

我正在使用replace在javascript中尝试regex字符串,但无法执行此操作。我在想的是:

var str = [{"Contact":["{"name":"abc","address": "xyz","PhoneNumber": "08976"}", "{"name":"abc","address": "xyz","PhoneNumber": "08976"}","{"name":"abc","address": "xyz","PhoneNumber": "08976"}","{"name":"abc","address": "xyz","PhoneNumber": "08976"}"]}]
str.replace(/"\\{/g,"\\{") // replace every instance of "{ with just {

我想用"{替换{的所有实例,只用}"替换}的所有实例。我怎么能一起做2次更换,1次更换我的错误,因为我正在使用的替代品实际上并没有发生。

3 个答案:

答案 0 :(得分:1)

使用{退出\一次。不需要在替换字符串中转义。

str.replace(/"\{/g,"{")
// "[{"Contact":[{"name":"abc","address": "xyz","PhoneNumber": "08976"}", {"name":"abc","address": "xyz","PhoneNumber": "08976"}",{"name":"abc","address": "xyz","PhoneNumber": "08976"}",{"name":"abc","address": "xyz","PhoneNumber": "08976"}"]}]"

BTW,问题中的str不是字符串文字。

答案 1 :(得分:1)

您可以在单个替换呼叫中进行两次替换:

var repl = str.replace(/"(\{)|(\})"/g, '$1$2');
  • 确保str是有效字符串
  • 您可以使用内置JSON解析来避免使用正则表达式

答案 2 :(得分:0)

如果你的意思是字符串是一个实际的字符串......

// Be sure that it's a string
var str = '[{"Contact":["{"name":"abc","address": "xyz","PhoneNumber": "08976"}", "{"name":"abc","address": "xyz","PhoneNumber": "08976"}","{"name":"abc","address": "xyz","PhoneNumber": "08976"}","{"name":"abc","address": "xyz","PhoneNumber": "08976"}"]}]';

// Assign the output to a variable and use single backslash to escape `{`. You're
// using the literal regex construct here / ... /
result = str.replace(/"(\{)|(\})"/g,"$1$2");

要将"{替换为{,将}"替换为},您可以使用捕获组,反向引用和“或”正则表达式运算符({{1} })。

jsfiddle