javascript - How do you convert a text file to CSV file while keeping text file format using JS? - Stack Overflow

I am reading in a text file with some data that looks like this:This is my fileshowing some datadata1

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 0
Add a ment  | 

2 Answers 2

Reset to default 5

You should be able to:

  1. split on line breaks
  2. split on white space
  3. join with mas
  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 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条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信