codenoob codenoob - 29 days ago 12
Javascript Question

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

Answer

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

Comments