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

Is it considered fundamentally inappropriate to call $scope.$digest within $scope.$on?

I recently inherited some AngularJS code, and my knowledge of both the codebase and Angular itself is limited. Within the code I inherited, there are instances where $scope.$digest is being called inside a $scope.$on method within a controller. Here's ...

Is there a way to verify if a given date falls within a specific range of dates in MongoDB?

{ "_id": { "$oid": "qwerty123" }, "Categories": [{ "mainmodels": [{ "submodels": [{ "price": "1500", "submodelname": "galaxyx21", }, { "price": "1700", "submodelname": "galaxys341", ...

Struggling to save a signature created with an HTML5 Canvas to the database

I've been on the hunt for a reliable signature capture script that can save signatures to MySQL, and I finally found one that fits the bill. However, there are two issues that need addressing: The canvas doesn't clear the signature when the c ...

Which is more efficient: Implementing caching on the frontend or on the

Currently, I am using ajax to send requests to the backend server, where operations are performed and responses are received: function getData() { new Ajax().getResponse() .then(function (response) { // handle response }) .catch(functi ...

Execute index.js code from index.html using NodeJS and Express

Currently, I am diving into the world of NodeJS and Express using Replit.com for a small project. The main objective is to develop a basic input field that, upon submission, will post to different channels such as Discord and Twitter. The piece of code be ...

Is it possible to share a MySQL connection for cross-module usage in Node/Express by utilizing promise-mysql?

Currently, I am trying to import and utilize a database module within one of my controllers. Despite successfully establishing the initial connection, I am encountering an error when accessing any of my routes through the browser: "Cannot read property ...

Overflow is causing interference with the scrollY value

I've been attempting to retrieve the scrollY value in my React app, but it seems to be affected by overflow-related issues. Below is the code snippet I used to access the scrollY value: import React from "react"; import { useEffect, use ...

Apply a chosen style to the element that was clicked on, while removing the style from the rest

Here is an example of my ul li structure: <div id="categoryTree"> <ul> <li id="cat_15"> <a class="hasSubCat" href="javascript:void(0);"><img src="images/icons/folder.gif" border="0" alt="Folder" title=" Folder ">N ...

Can one validate a single route parameter on its own?

Imagine a scenario where the route is structured as follows: companies/{companyId}/departments/{departmentId}/employees How can we validate each of the resource ids (companyId, departmentId) separately? I attempted the following approach, but unfortunate ...

Interactive image rotator featuring navigation buttons for next and previous slides

I recently followed a tutorial from W3Schools Now, I am looking to enhance it by adding previous / next buttons for the indicators, rather than for the slider itself Here is what I aim to accomplish: Below is the code snippet that I have been working on ...

Error message: The Liferay JavaScript Function has not been defined

I am a newcomer to Liferay and have been attempting to utilize Ajax within my scripts, but unfortunately, the code does not seem to load correctly in the browser. I even tried testing it by simply adding an alert. Every time I try, I encounter the "functi ...

Updating Angular components by consolidating multiple inputs and outputs into a unified configuration object

When I develop components, they often begin with numerous @Input and @Output properties. However, as I continue to add more properties, I find it beneficial to transition to utilizing a single config object as the input. For instance, consider a component ...

Implementing the sticky positioning property to keep a div container fixed at the bottom of the page

As Bootstrap 4 no longer supports .affix, I had to look for an alternative solution to keep a box fixed. I needed a div container to remain fixed as you scroll to it. My current workaround is using: .fixedcard{ position: sticky; top:75%; } However, th ...

Leveraging the result of one ajax function within a different ajax function

My current project involves the following steps: 1. User creates a template with various elements. 2. When the user clicks a button: *The first ajax function establishes a new entry in the custom template database. *The second ajax function retrieves the ...

Encountering an issue while attempting to deploy a contract using Truffle-contract from Node.js

I encountered an error while following the instructions in this documentation: https://www.npmjs.com/package/truffle-contract Every time I try to execute the deploy function, I am faced with this error. import Web3 from 'web3'; import propertyC ...

Issue: Unable to locate the 'express' module while executing on Azure

I am encountering an issue with my node.js app while deploying it on Azure. It runs perfectly fine locally using express, but on Azure, I am getting the following error: Application has thrown an uncaught exception and is terminated: Error: Cannot find mo ...

Using a Javascript plugin in Laravel with Vue by importing it into the project

Currently, I am in the process of creating a Vue component by utilizing the functionalities provided by the JavaScript plugin known as Cropper JS. The application is developed using Laravel 5.6. Initially, I installed Cropper JS via NPM: npm install cropp ...

"Adjusting Material UI Select Size - A Guide to Resizing Your

Struggling with getting Material UI selects to work properly with height and width using 'vh' and 'vw', as well as adjusting text size with 'vh'. The boxes have the correct size, but the label text is no longer centered due t ...

Data compilation query

Using Node.js with mongoose as the ORM, I have a collection of documents structured like below: I am trying to calculate the average time for the createdAt field in ISO String format, specifically focusing on the duration in hours while grouping by the ca ...

Encountering "environment.prod.ts path does not exist in file replacements" error while Dockerizing Angular build

I am encountering an issue with a Dockerfile that throws an error during the build process. I attempted to install the angular/cli globally and run ng build --prod using a separate RUN command, but the same error persists. Dockerfile FROM node:12.17.0-al ...