简体   繁体   中英

JavaScript: regex for “split” function to exclude commas and line breaks

I have text file with following structure:

2013-12-31 15:42,1
2013-12-31 15:45,1
2013-12-31 15:45,0
2013-12-31 16:18,0
2013-12-31 16:18,1
2013-12-31 16:27,1
2013-12-31 16:27,0
2013-12-31 17:11,0
2013-12-31 17:11,1
2013-12-31 18:11,1
2013-12-31 18:11,0

I am importing it by get():

$.get('graph_data.txt', function(data){
...}

That is working fine. Later I am parsing this data to array by:

var array3 = data.split("\n");

But what I need to do is to split it either by comma or line break. I know that split can get regular expression but all the attempts that I did were unsuccessful:

.split("[,\\n]");
.split("/,|\s/");
.split("/,|\s/m");

What works for me was to do it in two steps - firstly split by one separator and later by second one:

var array3 = data.split("\n")[0].split(",");
var array5 = data.split("\n")[1].split(",");

But this is crazy if I have more data in the file.


To throw more light on what I want to achieve: I need to get array of coordainates used to draw a chart. The first value is date and second is either 0 or 1.

var line=[
    ['2013-12-31 15:42',1],
    ['2013-12-31 15:45',1],

    ['2013-12-31 15:45',0],
    ['2013-12-31 16:18',0],

    ['2013-12-31 16:18',1],
    ['2013-12-31 16:27',1],

    ['2013-12-31 16:27',0],
    ['2013-12-31 17:11',0],

    ['2013-12-31 17:11',1],
    ['2013-12-31 18:11',1],

    ['2013-12-31 18:11',0]
];

I am doing that by mapping second string in each pair to int:

var a1 = [array3[0], array5[0]];
var a2 = [array3[1], array5[1]];
var line1 = a1.map(function(e,i){ return [e, parseInt(a2[i]) ] }); 

Do you have an idea how can I deal with mentioned split function to make it work with two separators in one shot?

var data = data.split("\n").map(function (line) {
    var line = line.split(",");
    return [ line[0], parseInt(line[1], 10) ];
}
console.log(data);

This will give you

[
    [ '2013-12-31 15:42', 1 ],
    [ '2013-12-31 15:45', 1 ],
    [ '2013-12-31 15:45', 0 ],
    [ '2013-12-31 16:18', 0 ],
    ..
]

You can't separate by rows and columns in one statement, nor do I see why you should.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM