Substituting text in a document by utilizing two separate arrays: one holding the original text to be found and another storing the corresponding text for

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?

Answer №1

I prefer consolidating multiple search strings into one regex with a custom replacer:

  var re = new RegExp(searchStrings.join("|"), "g")
    var result = data.replace(re, it => replacementStrings[searchStrings.indexOf(it)]);

This way, the data only needs to be traversed once.

If opting for a loop approach, it is recommended to overwrite data instead of result. This allows the replaced version to undergo further replacements in subsequent iterations:

 for(var n= 1; n <= searchStrings.length - 1; n++){
    data = data.replace(new RegExp(searchStrings[n], "g"), replacementStrings[n]); 
 }   

Answer №2

After successfully finding a solution to the problem, I have realized that it may not be as efficient as it could be. Below is the code snippet that loops through both arrays and executes find/replace on the file:

fs.readFile("./fileName.L5X", "utf8", function(err, data){
    if(err){return console.log(err)}        

    for(var n= 1; n <= searchStrings.length - 1; n++){

        while(data.includes(searchStrings[n])){
            data = data.replace(searchStrings[n], replacementStrings[n]); 
        }        
    }
    //write the modified data back into the file
    fs.writeFile("./fileName.L5X", data, "utf8", function(err){
        if(err){return console.log(err)}
    })
})

However, using the while loop has caused the code to run slower than desired. The searchString array contains 7500 strings and the fileName.L5X file itself is quite large (around 6MB).

If you have any suggestions or alternative methods to improve the operation, please feel free to share them.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountered an error while trying to load a resource: the server returned a 404 (Not Found) status code while attempting to edit a form using

I am facing an issue with navigating to the correct path after editing a form in React. Following the update, the web page refreshes and unexpectedly logs me out of the site even though there are no errors detected during the process. The console displays ...

What method does AngularJS use to distinguish between these two properties?

I grasp the concept that ng-model generates a property that corresponds to the {{name}}. How does AngularJS distinguish between the {{name}} derived from the ng-model and the {{name}} originating from the ng-repeat/ng-init? <section class="section"> ...

What is the most effective way to transfer a variable between two javascript files?

I am currently working on customizing the code from a github repository found at Github repo for integration with Google App Engine. However, I have encountered an issue when trying to pass a variable from /app.js to /books/crud.js. Although I have success ...

The Javascript function call from the <img src="myFunction()"> is malfunctioning

I am looking to dynamically pass the URL of an image using a JavaScript function. <head> <script> function myFunction() { var str1 = "somepictureurl.png"; return str1; } </script> </head> <body> <img src="myFu ...

Stop the button event from triggering

Although Sharepoint is available, I believe this question pertains more to javascript and cross browsing than Sharepoint. In my Sharepoint environment, I have a custom ribbon button that should trigger a workflow for a specific element in my library. I wo ...

Enhance local rotation of objects in Three.js

I am working on creating a spaceship-like object with controls, and I have learned that I need to use quaternions to achieve this. To start, I am attempting to make a cube rotate to the left when the A key is pressed. Here is the code I have written for th ...

What is the best way to dynamically change className in React.js?

I am working on a Collection component where I need to change the classNames of both the Collection component and its first sibling component when a div is clicked. Even though I tried using UseState, I could only manage to change the className of the cur ...

Having trouble getting a ForEach loop to work within promises when using mongoose?

Hey everyone! I'm diving into the world of nodeJs and working on a project that involves pushing certain values into an array. Unfortunately, my code isn't behaving as expected, and I suspect it has something to do with promises. Here's the ...

Implementing a 1-second delay in a Vue.js delete request

I have items that are retrieved through API calls and users can add them to their cart. They also have the option to delete items from the cart, but I want the item to be visually removed from the front-end after 1 second because of an animation on the del ...

What are the steps for configuring clusters in an expressjs 4.x application?

I currently have an expressjs generated app that is configured with socket io and I want to incorporate nodejs clusters into it. However, the challenge lies in the fact that in Express 4.x, the server listening configuration now resides in the bin/www file ...

Various Plus/Minus Containers

One issue I am facing is that when using multiple counters on the same page, my - and + buttons to decrease or increase the number in a text box do not function properly. The script provided below works for one counter. How can I modify this code so that ...

Error message "env: '/bin/flask': No such file or directory" pops up while executing the command "npm run start-backend"

Currently on the hunt for a super basic website template that combines Flask and React. I've been using this repository and carefully following the installation steps laid out https://github.com/Faruqt/React-Flask Working on Windows 10 using git Bas ...

Optimizing the Placement of Dynamic Google Maps

After setting up a responsive Google map using this jsFiddle and guidance from this stack overflow post, I encountered an issue. How can I keep the map centered on the marker across various viewports and browser sizes? I came across a solution in this res ...

Change the value of a single element in an array using a component in ReactJS

I'm attempting to pass an array value to a specific index in one component and then assign a desired value from the child component. I need it to work this way because I'm developing a survey app where the number of questions can vary. This is j ...

Having difficulty accessing a PHP ajax post request

I've scoured every resource but can't seem to find a solution to this issue. I'm in the process of writing an ajax script, however, I am struggling to retrieve the correct value from the POST request. Here is the code I have so far: <t ...

Is it possible to send two parameters to a JavaScript function using HTML?

Seeking help to develop an .html page where two string inputs are passed as parameters to a .js function, which then returns the longer of the two strings based on their lengths. Initially, I successfully created a functional .js script in VS CODE. Here i ...

Exploring methods to trace the factory's property that is receiving updates from another factory within AngularJS

Hey there, I'm new to Angularjs and I have a bunch of factories in my application. The situation is, let's say we have obj1 in factoryA. Whenever I console.log(obj1), it displays numerous properties associated with it. This object is being update ...

Tips for arranging the items within the slider according to the specified direction (rtl, ltr) in the Owl Carousel slider for Angular

Is there a way to dynamically change the direction of the owl-carousel-o angular slider based on the selected language? Currently, I have set rtl: true in the owl-carousel configuration during initialization. However, when the user switches to a different ...

Tips for updating a plugin from phonegap 2.5 to the most recent version 3.1, and the steps to follow when including a new plugin in phonegap

$('#sendSms').click(function(e){ alert("Sending SMS in progress");//After this alert, I encountered continuous errors and couldn't determine the root cause var smsInboxPlugin = cordova.require('cordova/plugin/smsinboxplugin'); ...

Transform the text area in preparation for a GET request

Trying to figure out how to pass the text from a textarea into the source attribute of an image tag while retaining all formatting, including line breaks. After some research, it seems that the best way to accomplish this is by base 64 encoding the text a ...