I am facing a challenge with replacing specific text strings in a file. I have two arrays - one containing the strings that need to be located and replaced, and the other containing the replacement strings.
fs.readFile("./fileName.L5X", "utf8", function(err, data){ if(err){return console.log(err)}
var result = data.replace(searchStrings[1], replacementStrings[1]);
//write the replacement result into file
fs.writeFile("./fileName.L5X", result, "utf8", function(err){ if(err){return console.log(err)} }) })
The issue is that this code only replaces the first occurrence of the string matching searchStrings[1]. I attempted to use a RegExp object for searching, but it didn't work as expected. For example, searchStrings[1] might be something like "B11[1].0".
Here's the alternative approach I tried using a RegExp object :
fs.readFile("./fileName.L5X", "utf8", function(err, data){ if(err){return console.log(err)}
var re = new RegExp(searchStrings[1], "g") var result = data.replace(re, replacementStrings[1]);
//write the replacement result into file
fs.writeFile("./fileName.L5X", result, "utf8", function(err){ if(err){return console.log(err)} }) })
In addition to this, I would like to iterate through the searchStrings array to find and replace all occurrences inside fileName.L5X. However, simply putting the above code snippet within a loop only seems to modify the last element from searchStrings within the file.
Below is an illustrative attempt where I tried to implement a looping mechanism for the find/replace process:
fs.readFile("./fileName.L5X", "utf8", function(err, data){ if(err){return console.log(err)}
for(var n= 1; n <= searchStrings.length - 1; n++){ var result = data.replace(searchStrings[n], replacementStrings[n]); }
//write the replacement result into file
fs.writeFile("./fileName.L5X", result, "utf8", function(err){ if(err){return console.log(err)} }) })
Could you suggest an efficient way to iterate through each string present in searchStrings and perform replacements in the file?