开发者

Javascript: Time and Info splitting

开发者 https://www.devze.com 2023-01-30 11:08 出处:网络
From server I get data as such: \"07.00 PROGRAM DESCRIPTION\" \"07.20 PROGRAM DESCRIPTION 2\" I want to split them into a 2 indexed array such as: [\"07.00\", \"PROGRAM DESC开发者_运维百科RIPTION 2

From server I get data as such:

"07.00 PROGRAM DESCRIPTION"
"07.20 PROGRAM DESCRIPTION 2"

I want to split them into a 2 indexed array such as: ["07.00", "PROGRAM DESC开发者_运维百科RIPTION 2"]. Regular split( " " ) would not work me as the description part contains severaral " " spaces.

I will be grateful for any suggestion.

Regards


You could use:

var parts = str.split(' '),
    time = parts.shift(),
    description = parts.join(' ');

or, to get your array:

var parts = str.split(' ');
parts[1] = parts.slice(1).join(' ');

;)


You need somekind of a pattern, which is reliable. If it's always the case that you need to split just between the first whitespace character to you can do:

var blub = "07.00 PROGRAM DESCRIPTION",
    pos  = blub.indexOf(" "),
    arr  = [];

arr[0] = blub.slice(0, pos);
arr[1] = blub.slice(pos + 1);

or you might just want to use regular expression. Since I don't pretend to be a genius on that field here is my little suggestion:

var blub = "07.00 PROGRAM DESCRIPTION",
    arr  = /(\d+\.\d+)\s(.*)/.exec(blub);


var pattern = /([0-9]{2}\.[0-9]{2})\s(.+)/;
var data = "07.00 PROGRAM DESCRIPTION";
var parsed = pattern.exec(data);

console.log(parsed); // (Array) ["07.00 PROGRAM DESCRIPTION", "07.00", "PROGRAM DESCRIPTION"]

this is flexible and easier to adapt in case the format changes (just change the pattern and use that var anywhere else in your code)


The substring method:

var time = row.substring(0,4);
var description = row.substring(5);

Or, with the split method:

row = row.split(" ",1);

The second parameter is the maximum number of splits... so it'll only split at the first space. Edit: this won't work. Use the first method instead.

0

精彩评论

暂无评论...
验证码 换一张
取 消