替换{和}

时间:2016-06-22 11:32:28

标签: javascript

有一个问题。 在JSON.stringify之后我有一个字符串:

value.value_new = {"apiunits":{"amount":"0"},"total":{"requests":"10","results":"10"},"project":{"projects":"1"}};

我想替换{和},我尝试这样做:

value.value_new = value.value_new.replace("/[{}]/g", " ");

value.value_new = value.value_new.replace("/{/g", " ");
value.value_new = value.value_new.replace("/}/g", " ");

但它不起作用。为什么呢?

2 个答案:

答案 0 :(得分:1)

我不确定你为什么要这样做或者你会对结果做什么,但我认为你想要的RegEx是:

var asString = '{"apiunits":{"amount":"0"},"total":{"requests":"10","results":"10"},"project":{"projects":"1"}};'

//Replace either curly with a space. Note in RegEx you have to escape the curly braces with a backslash
var replaced = asString.replace(/\{|\}/gi, ' ');

console.log(replaced);
//outputs -->" "apiunits": "amount":"0" ,"total": "requests":"10","results":"10" ,"project": "projects":"1"  ;"

在我的示例中,我将管道用于“或”,但如果花括号被转义,您之前的任何尝试都会起作用:

value = value.replace("/[\{\}]/g", " ");

 value = value.replace("/\{/g", " ");
 value = value.replace("/\}/g", " ");

答案 1 :(得分:1)

value.value_new不是字符串,因此您无法在其上使用replace函数。

如果您只需要不带括号的字符串,则可以使用此方法:

var value = {};
value.value_new = '{"apiunits":{"amount":"0"},"total":{"requests":"10","results":"10"},"project":{"projects":"1"}}';

String.prototype.replaceAll = function(str1, str2, ignore) 
{
    return this.replace(new RegExp(str1.replace(/([\/\,\!\\\^\$\{\}\[\]\(\)\.\*\+\?\|\<\>\-\&])/g,"\\$&"),(ignore?"gi":"g")),(typeof(str2)=="string")?str2.replace(/\$/g,"$$$$"):str2);
} 

value.value_new = value.value_new.replaceAll("{", '');
value.value_new = value.value_new.replaceAll("}", '');


console.log(value.value_new); // You'll have the string that you want