codenoob
codenoob

Reputation: 539

How to Regex split time string

In javascript, I have a time string var time = "12:30:49PM"

I want to separate the hour, min, sec and AM/PM from that string.

Browsing stackoverflow I was able to find the following regex that split hour, min and Am/pm, but I am very bad at regex so I cant work out how to do the sec.

 var hours = Number(time.match(/^(\d+)/)[1]);
 var minutes = Number(time.match(/:(\d+)/)[1]);
 var AMPM = time.match(/([AaPp][Mm])$/)[1];

how to get the second via regex

Upvotes: 1

Views: 2868

Answers (6)

BitJunky
BitJunky

Reputation: 1

How about!:

console.log(DateTimeFormat(new Date(), '`The Year is ${y} DateTime is: ${m}/${d}/${y} Time is: ${h}:${M}:${s}   `'))

function DateTimeFormat(dt, fmt)
{
    [y, m, d, h, M, s, ms] =  new 
    Date(dt).toLocaleString('UTC').match(/\d+/g)
    return eval(fmt)
}

Upvotes: 0

naoufal bardouni
naoufal bardouni

Reputation: 251

var sec = Number(time.match(/:([0-9][0-9])/ig)[1].replace(":",""))

Upvotes: 0

samanime
samanime

Reputation: 26625

In your example, you would simply do something like:

var time = "12:30:49PM";   
var hours = Number(time.match(/^(\d+)/)[1]);
var minutes = Number(time.match(/:(\d+)/)[1]);
var AMPM = time.match(/([AaPp][Mm])$/)[1];
var seconds = Number(time.match(/:(\d+):(\d+)/)[2]);
console.log(hours, ":", minutes, ":", seconds, AMPM);  

However, it'd be more effecient to get everything in one call:

var time = "12:30:49AM";
var matches = time.match(/^(\d+):(\d+):(\d+)([AP]M)$/i);
var hours = matches[1];
var minutes = matches[2];
var seconds = matches[3];
var AMPM = matches[4];
console.log(hours, ":", minutes, ":", seconds, AMPM);

Upvotes: 5

adeneo
adeneo

Reputation: 318352

Just split on colon and the (P\A)M part

var time  = "12:30:49PM";
var parts = time.split(/:|(\DM)/).filter(Boolean);

console.log(parts)

Upvotes: 1

Thomas Ayoub
Thomas Ayoub

Reputation: 29481

You can use it like so:

var time = "12:30:49PM"
var hours = Number(time.match(/^(\d+)/)[1]);
var minutes = Number(time.match(/:(\d+)/)[1]);
var sec = Number(time.match(/:(\d+)\D+$/)[1]);
var AMPM = time.match(/([ap]m)$/i)[1];
console.log(hours);
console.log(minutes);
console.log(sec);
console.log(AMPM);

Upvotes: 1

Ori Drori
Ori Drori

Reputation: 193258

You can use a combination of regex with ES6 array destructuring:

const time = "12:30:49PM"
const [hour, min, sec, period] = time.match(/\d+|\w+/g);

console.log(hour, min, sec, period);

Upvotes: 5

Related Questions