2

I have a json file in which I want to replace two words with two new words using fs of node js. I read the solution to a similar query on Replace a string in a file using nodejs. Then I tried the following code snippet but it replaces only a single word. I need to run it multiple times to replace multiple words.

Here is the code snippet:

var fs = require('fs')
fs.readFile('C:\\Data\\sr4_Intellij\\newman\\Collections\\api_collection.json', 'utf8', function (err,data) {
  if (err) {
    return console.log(err);
  }
  var result1 = data.replace(/{{Name}}/g, 'abc');
  var result2 = data.replace(/{{Address}}/g, 'xyz');
  var arr1 = [result1,result2]
  console.log(arr1[0]);

  fs.writeFile('C:\\Data\\sr4_Intellij\\newman\\Collections\\api_collection.json', arr1, 'utf8', function (err) {
     if (err) return console.log(err);
  });

});
Yahia
  • 805
  • 7
  • 25
Saurav Rath
  • 91
  • 1
  • 3
  • 11

1 Answers1

4

You need to do the second replace on the result of the first replace. data isn't changed by replace; replace returns a new string with the change.

So:

var result = data.replace(/{{Name}}/g, 'abc')
                 .replace(/{{Address}}/g, 'xyz');

...then write result to the file.

Alternately, and this particularly useful if it's a large file or you have lots of different things to replace, use a single replace with a callback:

var replacements = Object.assign(Object.create(null), {
    "{{Name}}": "abc",
    "{{Address}}": "xyz"
    // ...and so on...
});

var result = data.replace(/{{[^}]+}}/g, function(m) {
    return replacements[m] || m;
});

Or with a Map:

var replacements = new Map([
    ["{{Name}}", "abc"],
    ["{{Address}}", "xyz"]
    // ...and so on...
]);

var result = data.replace(/{{[^}]+}}/g, function(m) {
    return replacements.get(m) || m;
});
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • Hi Crowder, one more question: Can we replace these strings in multiple files at at a time ? Like writing into multiple files at a time. Thanks for your insights into this. – Saurav Rath Nov 07 '17 at 10:26
  • @SauravRath: Not *at the same time* (unless you spawn [child processes](https://nodejs.org/api/child_process.html#child_process_child_process) to do it), but you certainly can in a loop. Beware the [closures in loops problem](http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example). – T.J. Crowder Nov 07 '17 at 10:28
  • nice solutions. Specifically I like that `.replace.replace` one. Thanks for the answer. – AMIC MING Dec 12 '19 at 23:36