Katie Katie - 8 months ago 18
Javascript Question

Get time from date and time using Regex

How do I extract

12:05 AM
7/16/2016 12:05:00 AM
using Regex?

I've made it this far

test = "7/16/2016 12:05:00 AM"
test.match(/^(\S+) (.*)/)[2]
> "12:05:00 AM"

but I can't figure out how to remove the seconds. Plus, if there's a simpler/more efficient way of doing what I'm trying to do, please let me know.

I would rather not rely on third-party libraries like moment.js

NOTE: My desired output is
12:05 AM
and not just


Look explicitly for the digits and colon, lopping off the last two before matching your am/pm:

var test = "7/16/16 12:05:00 AM";
var matches = test.match(/(\d\d:\d\d):\d\d(\s[ap]m)/i);
var time = matches && matches.length > 2 && (matches[1] + matches[2]);
// time === "12:05 AM"