0

I am new to javascript and have this code which will replace the string from A to B, but if there is multiple records of As, it will only replace the first A, while the remaining will be remain as A. Note that the stringify is called twice.

"success": function(json) {
    var old = JSON.stringify(json).replace('"新交易"', '"待审核"');
    var newdata = JSON.parse(old);

    var old = JSON.stringify(newdata).replace('"批准"', '"已充值"');
    var newdata = JSON.parse(old);
    fnCallback(newdata);
}
isvforall
  • 8,768
  • 6
  • 35
  • 50
MuthaFury
  • 805
  • 1
  • 7
  • 22

2 Answers2

0

This has little to do with JSON. As documented:

To perform a global search and replace, include the g switch in the regular expression.

So change this:

replace('"新交易"', '"待审核"')

... into this:

replace(/"新交易"/g, '"待审核"')
Álvaro González
  • 142,137
  • 41
  • 261
  • 360
0

To replace every word in your context use Regular Expressions. So check this example to see how it works:

    var someText = '"新交易""新交易""新交易""新交易""新交易""新交易""新交易""新交易"';
    var someText2 = '"批准""批准""批准""批准""批准""批准""批准""批准""批准""批准"';
    var old = someText.replace(/"新交易"/g, '"replaced"');
    var stuff = someText2.replace(/"批准"/g, '"已充值"');

https://jsfiddle.net/n1otvpy1/

ArianJM
  • 676
  • 12
  • 25
jlcv
  • 142
  • 1
  • 8