Substitute the symbol combination (][) with a comma within Node.js

Currently, I am utilizing Node JS along with the replace-in-file library for my project.

Within a specific file named functions.js, I have implemented various functions.

Furthermore, in another file named index.js, I have added code to call these functions.

Initially when I run the script, everything works smoothly. However, upon relaunching the script, the replacement of '][' with ',' does not occur as expected.

In Function.js:


var priority = "";
var expectedValue = "";
var score1 = "";
var score2 = "";

/* some function*/

function generateJSON(key){
    var table = []

    // JSON object structure

    table.push({
        "executionDate": date,
        "issueID": key,
        "priority":{
            "jira": priority, 
            "computed": score1
        },
        "expectedValue":{
            "jira": expected, 
            "computed": score2
        }
    })

    var json = JSON.stringify(table,null, 2);

    fs.appendFile('templateLog1.json', json, 'utf8', function (err) {
        if (err) console.error(err);
    });

}

function replaceCaracter(){
    const options = {
        files: 'templateLog1.json',
        from: '][',
        to: ',',
    };

    replace(options, (error, results) => {
        if (error) {
            return console.error('Error occurred:', error);
        }
        console.log('Replacement results:', results);
    });
}

In Index.js:


setTimeout(function() {
    functions.getAllIssueForSCII().then(function(json){
        for (let i=0; i < json.issues.length; i++){
            functions.generateJSON(json.issues[i].key);
            functions.replaceCaracter();
        }

    });
}, 1000)

Actual Result :


[
{
    "executionDate": 1556197884153,
    "issueID": "SCII-10",
    "priority": {
    "jira": "Lowest",
    "computed": -25
    },
    "expectedValue": {
    "jira": "Low",
    "computed": -10
    }
}
,
{
    "executionDate": 1556197896877,
    "issueID": "SCII-7",
    "priority": {
    "jira": "Low",
    "computed": -10
    },
    "expectedValue": {
    "jira": "Low",
    "computed": -10
    }
}
]

Expected Result:


[
{
    "executionDate": 1556197884153,
    "issueID": "SCII-10",
    "priority": {
    "jira": "Lowest",
    "computed": -25
    },
    "expectedValue": {
    "jira": "Low",
    "computed": -10
    }
}
,
{
    "executionDate": 1556197884153,
    "issueID": "SCII-7",
    "priority": {
    "jira": "Low",
    "computed": -10
    },
    "expectedValue": {
    "jira": "Low",
    "computed": -10
    }
}
,
{
    "executionDate": 1556197896877,
    "issueID": "SCII-10",
    "priority": {
    "jira": "Lowest",
    "computed": -25
    },
    "expectedValue": {
    "jira": "Low",
    "computed": -10
    }
}
,
{
    "executionDate": 1556197896877,
    "issueID": "SCII-7",
    "priority": {
    "jira": "Low",
    "computed": -10
    },
    "expectedValue": {
    "jira": "Low",
    "computed": -10
    }
}
]

Answer №1

This mistake is quite common. You'll notice that the first instance of ][ has been successfully replaced.

This issue often arises when utilizing the String.replace() method with a basic string as the initial parameter (the string being replaced).

The solution is to employ a regular expression with the global flag. Try substituting '][' with /]\[/g in the options object.

For more information on the String.replace method: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace

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

Retrieve data using Ajax querying from a specific data source

Currently, I am attempting to construct a custom query using Ajax to interact with PHP/MySQL. Here is what I have so far: Javascript code: var i=2; fetchFromDBPHP("name", "tblperson", "id="+i); function fetchFromDBPHP(column, table, condition) { ...

Adding a break in a CardHeader element subtitle in MaterialUI using ReactJS

I have been working with older Material UI components (Version 0.20.1). Below is an excerpt of my code: return( <> <Card> <CardHeader actAsExpander={true} showExpandableButton={true} title = {user.name} ...

Activate a tooltip in Vuetify

I'm utilizing vuetify and have implemented a tooltip feature on a button. However, I do not want the tooltip to be displayed on hover or click; instead, I would like it to appear when a specific event is triggered. translate.vue <v-tooltip v-model ...

The functionality of the angularjs class seems to be malfunctioning

I'm a new learner of angularjs and I've created a simple page below. I have a style called "item" that I'm trying to apply to a div, but it's not working. However, if I use inline style, then it works fine. Can someone please help me f ...

Navigating external pages with Vue Router

Could really use some assistance. I've got a JSON file filled with various URL links, some internal and some external. This is what the JSON structure looks like: [ {stuff..., "Url":"https://www.google.com/", stuff..}, {stuff... ...

Utilizing React Router V4 to Render Dual Components on a Single Route

Looking for help with these routes <Route exact path={`/admin/caters/:id`} component={Cater} /> <Route exact path={'/admin/caters/create'} component={CreateCater} /> After visiting the first route, I see a cater with an ID display ...

Issues with response functionality in Node.js (Openshift) using express

I am currently working with OpenShift and Node.js to calculate the average rating for each result. However, I am facing an issue where the response is not being displayed even though the console logs show the correct data. The console displays 3.9454323, ...

Using Formik with Material UI's TextField component and passing a 'label' prop to the Field component

Currently, I am in the process of creating a form with Formik and Material UI. I have implemented the Formik component as follows: Within my Input component, the following code is used: const Input = ({ field, form: { errors } }) => { const errorMes ...

Sending a JSON object using PostAsJsonAsync method without considering the name attribute specified

One of my static methods is responsible for posting data in the following manner: public static Task<HttpResponseMessage> PostExAsync<TValue>(this HttpClient client, string path, TValue value, CancellationToken ct = default) { if (value == ...

What is the best way to integrate react-final-form with material-ui-chip-input in a seamless manner

Currently, I am utilizing Material UI Chip Input wrapped with Field from react-final-form. https://i.sstatic.net/vJKM1.jpg The main objective is to restrict the number of "CHIPS" to a maximum of 5. Chips serve as concise elements representing inputs, at ...

Which specific event in NextJS is triggered only during the initial load?

I am working on a NextJS app and I want to implement an initial loading screen that only appears during the first load. Currently, the loading screen pops up not only on the initial load but also whenever a link is clicked that directs the user back to the ...

Tips on resolving the issue of "undefined in VueJS"

I have just developed a new component in VueJS and defined two methods. One method is an action (vuex) and the other one is a regular method. actionTypes.js const TOGGLE_PREVIEW = 'togglePreview'; component method: { ...mapActions([actionTy ...

Selecting radio buttons across multiple div classes

I've been struggling to programmatically select specific radio buttons on a webpage. My goal is to automatically choose the second option in each group of radio buttons, but I'm getting lost in the syntax. Unlike most examples I've found on ...

Here's a new take on the topic: "Implementing image change functionality for a specific div in Angular 8 using data from a loop"

I need to create a list with dynamic data using a loop. When I click on any item in the list, I want the image associated with that item to change to a second image (dummyimage.com/300.png/09f/fff) to indicate it's active. This change should persist e ...

What could be causing the background color not to change on the HTML page with Bootstrap?

Learning html, bootstrap, and css styling can be a confusing endeavor. Sometimes things don't work as expected, like changing the background color. Despite following what seems like a simple solution after googling, the background color remains unchan ...

What could be causing my node server's REST endpoints to not function properly?

Here is a snippet of my index.js file: var http = require('http'); var express = require('express'); var path = require('path'); var bodyParser = require('body-parser') var app = express(); var currentVideo = &apos ...

Click here to navigate to the same or a different page using an anchor

I'm currently implementing this code: $(function() { $('a[href*=#]:not([href=#])').click(function() { if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostna ...

Instantly: Retrieve data from multiple levels of JSON

https://i.sstatic.net/d5RQX.png I need to extract the name and state of inspections for each service from a complex JSON structure. Despite trying the code snippet below, I am still facing issues: TRANSFORM(CAST(JSON_PARSE(json_format(json_extract(json_e ...

Is there a way for me to retrieve dynamic text?

I used an "IF" statement to display dynamic text - if it's null, show something, otherwise show something else. However, I am getting a blank result. What did I do wrong? <View style={styles.rightContainer}> { () =>{ if(t ...

Node.js cannot access the uploaded image data as it has been defined as undefined

I have encountered an issue while sending an image file through ajax to my Node.js server. Upon attempting to view the file data, it returns 'undefined'. Here is a snippet from my app.js file: var express = require("express"); var app ...