Reputation: 119
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
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
Reputation: 92460
You should be able to:
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