Hellnar
Hellnar

Reputation: 64803

Javascript: Time and Info splitting

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 DESCRIPTION 2"]. Regular split( " " ) would not work me as the description part contains severaral " " spaces.

I will be grateful for any suggestion.

Regards

Upvotes: 4

Views: 166

Answers (4)

jAndy
jAndy

Reputation: 236022

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);

Upvotes: 2

Ege Özcan
Ege Özcan

Reputation: 14269

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)

Upvotes: 1

Nathan
Nathan

Reputation: 11149

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.

Upvotes: 0

Spiny Norman
Spiny Norman

Reputation: 8337

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(' ');

;)

Upvotes: 2

Related Questions