How do I extract 12:05 AM
from 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 12:05
How do I extract 12:05 AM
from 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 12:05
- search for the first colon (:) and retrive the 2 chars before and after it. – ClearBoth Commented Jul 15, 2016 at 19:06
3 Answers
Reset to default 4Look explicitly for the digits and colon, lopping off the last two before matching your am/pm. We also make the second hour digit optional, in case we are just matching against "3:14:16 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[1] + matches[2]);
// time === "12:05 AM"
Just to note for fullness of regex, you could also use curly braces to determine the number of digits to count (I didn't above, because it's more characters in the end when it's just 1-2). Both the following and above will match the same string:
var matches = test.match(/(\d{1,2}:\d{2}):\d{2}(\s[ap]m)/i;
A simple and short alternative is to match the parts you don't want, and replace them by empty strings.
test.replace(/^\S*\s*|:\d\d(?!:)/g, "")
Explanation:
^\S*\s*
- matches the date and the first space:\d\d(?!:)
- matches the seconds and the colon preceding it; the negative lookahead prevents the pattern from matching the minutesg
- 'global' flag; need this because we have two matches to be replaced
Try it here:
window.go = function() {
var input = document.getElementById("input").value;
var output = input.replace(/^\S*\s*|:\d\d(?!:)/g, "");
document.getElementById("output").value = output;
};
<input id="input" value="7/16/2016 12:05:00 AM">
<button onclick="go()">Click me!</button>
<input id="output">
This is an easier way:
var time = test.split(' ')[1]
time = time.substring(0, time.length - 3)+' '+test.split(' ')[2]
Also, if you need to work with dates and time I would suggest Moment.js
moment(test).format('h:mm A')