Maxii Paguera
Maxii Paguera

Reputation: 33

Removing "," at the beginning of a line CSV

i want to convert a .csv file and write a new one. However I am not able to remove the first , i am kinda stuck here and it is driving me crazy. This is my code:

    var extractedtasks = tasks.slice(0, 3)
    var extractedtasksformated = extractedtasks.toString().replace(/,$/g, "\n")

    let csvformat = "EMAIL,PASSWORD,MAILBOX"
    fs.writeFileSync(tasklocation[0], csvformat + "\n" + extractedtasksformated.replace(/,^/g, 
    ""))
    console.log(chalk.green("Successfully updated the CSV file"))

That's the output i am getting in the newly generated file

EMAIL,PASSWORD,MAILBOX
[email protected],Password123,[email protected]:password
,[email protected],Password123,[email protected]:password
,[email protected],Password123,[email protected]:password

Output extractedtasks:

[
  '[email protected],Password123,[email protected]:password\r',
  '[email protected],Password123,[email protected]:password\r',
  '[email protected],Password123,[email protected]:password\r'
]

Output extractedtasksformated:

,[email protected],Password123,[email protected]:[email protected]:password

Upvotes: 0

Views: 154

Answers (1)

rewritten
rewritten

Reputation: 16435

Because extractedtasks is an array, instead of converting it to a string you should just join it with the expected separator:

extractedtasks = [
  '[email protected],Password123,[email protected]:password\r',
  '[email protected],Password123,[email protected]:password\r',
  '[email protected],Password123,[email protected]:password\r'
]

extractedtasksJoined = extractedtasks.join("\n")
// "[email protected],Password123,[email protected]:password\r\[email protected]..."

// depending on the target line separator, you should also probably
// remove the "\r"
extractedtasksJoined = extractedtasksJoined.replace("\r", "")

// finally
fs.writeFileSync(tasklocation[0], csvformat + "\n" + extractedtasksJoined + "\n")

Upvotes: 1

Related Questions