ND's
ND's

Reputation: 2215

convert string having time to array in javascript

var timeString=$('.csstdhighlight').closest('tr').find('td:first-child').text();

//getting timestrinfg like this
timeString="07:15 PM07:30 PM07:45 PM08:00 PM08:15 PM08:30 PM08:45 PM";

I have to convert string to array.
So that I can get Start time and end time from array arra[0] will get Start time, array[array.length-1] will get end time

Upvotes: 0

Views: 168

Answers (2)

Ja͢ck
Ja͢ck

Reputation: 173572

A regular expression would do the job; for just the start and stop times:

var re = /^(\d{2}:\d{2} [AP]M).*(\d{2}:\d{2} [AP]M)$/,
match = timeString.match(re);

console.log(match[1]); // "07:15 PM"
console.log(match[2]); // "08:45 PM"

Alternatively, match all time patterns:

var re = /\d{2}:\d{2} [AP]M/g;
console.log(timeString.match(re));
// ["07:15 PM", "07:30 PM", "07:45 PM", "08:00 PM", "08:15 PM", "08:30 PM", "08:45 PM"]

Update

Seeing how the regular expression for each time has a constant length and you only want the first and last, you can even do this:

timeString.substr(0, 8); // "07:15 PM"
timeString.substr(-8);   // "08:45 PM"

Upvotes: 4

Pranav Negandhi
Pranav Negandhi

Reputation: 1624

Use the split() method.

var n = timeString.split(" ");
start = n[0];
end = n[n.length - 1];

Upvotes: 0

Related Questions