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