有问题。 在 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", " ");
但它不起作用。为什么?
最佳答案
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
关于javascript - 替换 { 和 },我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37966797/