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);
  });

});
1
  • javascript does not support recursive matching for regexp natively, maybe you want to use a library for that Commented Nov 7, 2017 at 9:13

1 Answer 1

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;
});
Sign up to request clarification or add additional context in comments.

3 Comments

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.
@SauravRath: Not at the same time (unless you spawn child processes to do it), but you certainly can in a loop. Beware the closures in loops problem.
nice solutions. Specifically I like that .replace.replace one. Thanks for the answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.