【问题标题】:Replace values in a string using JavaScript使用 JavaScript 替换字符串中的值
【发布时间】:2016-04-22 21:42:18
【问题描述】:

我想使用 JavaScript 将下面 JSON 字符串中的所有字符串值替换为空字符串,将 true 替换为 false,并将数组(方括号)中的 1 替换为 0。

补充信息:JSON字符串放在一个字符串类型变量中。

注意:属性是动态的。这意味着有时我可以拥有 MobilePhone 并且会出现此属性丢失的情况。所以引用属性名称不是一种选择。

我的 JSON 字符串:

{"MobilePhone":true,"ToDeleteIndex":1,"BusinessPhone":true,"ApplicantType":"HOLDER","Title":"Mr","FirstName":"Andrew","RemoveApplicant":[1,null]}

预期结果:

{"MobilePhone":false,"ToDeleteIndex":1,"BusinessPhone":false,"ApplicantType":"","Title":"","FirstName":"","RemoveApplicant":[0,null]}

【问题讨论】:

  • 为什么不使用JSON.parse()将其转换为对象,然后直接处理值而不是替换字符串中的值?
  • @Barmar 那么设置值的下一步是什么,因为我不知道将传递哪些属性?

标签: javascript json


【解决方案1】:

在JSON.parse 之后,试试这个:

const data = {
    "MobilePhone": true,
    "ToDeleteIndex": 1,
    "BusinessPhone": true,
    "ApplicantType": "HOLDER",
    "Title": "Mr",
    "FirstName": "Andrew",
    "RemoveApplicant": [1, null]
  }
  //string to empty string, true to false, and 1 to 0 (in array)
trans = {
  string: function(x) {return x= ''},
  boolean: function(x) {
    if (x)
      x = false;
    return x;
  },
  object: function(x) {
    if (Array.isArray(x))
      x.map(function(z) { if (z === 1) z = 0; return z});
    return x;
  }
}

const r = Object.keys(data).map(function(x) {
  const val = trans[typeof(data[x])] ? trans[typeof(data[x])](data[x]) : data[x];
  return {[x]: val};
})
console.log(r)

【讨论】:

  • 我收到一个错误“未知标识符”的逗号 --> 字符串:(x) => '',
  • @Ahmad on chrome v49 我没有收到任何错误,您使用的是什么浏览器?反正(x) => ''是一个es6箭头函数语法,你可以用function(x){ return x = ' '; }代替它,我会更新我的答案。
【解决方案2】:

试试这个DEMO

var data = JSON.parse('{"MobilePhone":true,"ToDeleteIndex":1,"BusinessPhone":true,"ApplicantType":"HOLDER","Title":"Mr","FirstName":"Andrew","RemoveApplicant":[1,null]}');

for (prop in data) {
  if (data[prop] === true) {
    data[prop] = false;
  } else if (typeof data[prop] == 'string') {
    data[prop] = '';
  } else if (Array.isArray(data[prop])) {
   data[prop] = data[prop].map(function(el) { return (el == 1) ? el = 0 : el});
  }
}

document.write(JSON.stringify(data));

【讨论】:

  • 首先你需要做data = JSON.parse(string);。
  • 你可能想要一个三等号比较为真。您也不应该将解决方案硬连接到数组的第一个元素。
  • @NenadVracar 数组中的值从 1 变为 null 而不是 0
【解决方案3】:

您可以在javascript中使用string Replace()函数。

如果您的 Json 在字符串变量中,则执行以下操作;

var str = "{'MobilePhone':true,'ToDeleteIndex':1}";//your json as string
var res = str.replace(new RegExp("true", 'g'), "false"); //replace true to false
var res = res.replace(new RegExp("1", 'g'), "0"); //replace 1 to 0
Console.Log(res); //{'MobilePhone':false,'ToDeleteIndex':0}

但是,请小心,因为此代码将所有出现的true 替换为false,将1 替换为0,无论它们在字符串中的位置如何。

【讨论】:

  • str.replace() 只替换第一个匹配项,除非您使用带有g 修饰符的正则表达式。
  • 并且将1 替换为0 也会将11 更改为00。
  • 在哪里用空字符串替换所有字符串值?
猜你喜欢
  • 2016-07-07
  • 2021-12-26
  • 2016-04-15
  • 1970-01-01
  • 2014-06-30
  • 1970-01-01
  • 2013-08-30
  • 1970-01-01
  • 2011-10-23
相关资源
最近更新 更多