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
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
Share Improve this question asked Dec 22, 2018 at 1:31 MauricioMauricio 1193 silver badges12 bronze badges 02 Answers
Reset to default 5You should be able to:
- split on line breaks
- split on white space
- join with mas
- 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 mas:
let s = `This is my file
showing some data
data1 = 12
data2 = 156`
console.log(s.replace(/[^\S\n]+/g, ','))
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 />"));
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745121723a4612452.html
评论列表(0条)