Mauricio
Mauricio

Reputation: 119

How do you convert a text file to CSV file while keeping text file format using JS?

I am reading in a text file with some data that looks like this:

This is my file
showing some data
data1 = 12
data2 = 156

I want to convert this data into a CSV file while keeping the same format of the text file, like this:

This,is,my,file
showing,some,data
data1,=,12
data2,=,156

My first attempt was to read the text file into a string. The split that string into an array, splitting it at every ' ' (space) char. However, that doesn't seem to work.

I also attempted to split the string into an array at every 'newline' char but it doesn't seem to work.

Can anyone guide me in the right direction? Or how should I go about doing this?

Thanks

Upvotes: 2

Views: 5907

Answers (2)

Vahe
Vahe

Reputation: 1841

Try str.replace(/ /g, ',');

Code

str = "This is my file\n\
showing some data\n\
data = 12\n\
data2 = 156";

document.write((str.replace(/ /g, ',')).replace(/\n/g,"<br />"));

Upvotes: 0

Mark
Mark

Reputation: 92460

You should be able to:

  1. split on line breaks
  2. split on white space
  3. join with commas
  4. join with new lines:

let s = `This is my file
showing some data
data1 = 12
data2 = 156`

let text = s.split('\n')                               // split lines
            .map(line => line.split(/\s+/).join(','))  // split spaces then join with ,
            .join('\n')                                // rejoin lines

console.log(text)

You could also just replace all non-linebreak whitespace with commas:

let s = `This is my file
showing some data
data1 = 12
data2 = 156`

console.log(s.replace(/[^\S\n]+/g, ','))

Upvotes: 5

Related Questions