Reputation: 2846
I am trying to split following (or similar) string "08-27-2015 07:25:00AM". Currently I use
var parts = date.split(/[^0-9a-zA-Z]+/g);
Which results in
["02", "27", "2012", "03", "25", "00AM"]
The problem is with the 00AM
part. I want it to be separated too. So the perfect result would be:
["02", "27", "2012", "03", "25", "00", "AM"]
Upvotes: 16
Views: 25761
Reputation:
If you're looking for sequences of letters or numbers, but not a sequence both mixed, you can do this...
"08-27-2015 07:25:00AM".match(/[a-zA-Z]+|[0-9]+/g)
resulting in...
["08", "27", "2015", "07", "25", "00", "AM"]
On either side of the |
, we have a sequence of one or more letters and a sequence of one or more numbers. So when it comes across a letter, it will gather all contiguous letters until it reaches a non-letter, at which point it gathers all contiguous numbers, and so on.
Any other character simply doesn't match so it doesn't become part of the result.
Upvotes: 45
Reputation: 31250
var date = "08-27-2015 07:25:00AM";
var parts = date.replace(/([AP]M)$/i, " $1").split(/[^0-9a-z]+/ig);
var date = "05June2012";
var parts = date.replace(/([a-z]+)/i, " $1 ").split(/[^0-9a-z]+/ig);
Upvotes: 2
Reputation: 9752
I would use a date library to parse the fields you want. That way you can handle multiple formats and not worry about parsing with regular expressions. While DateJS is a little old it performs well for parsing.
Upvotes: 0
Reputation: 4459
If the date is always in that format you can use:
var parts = date.match(/([0-9]{2})-([0-9]{2})-([0-9]{4})\s([0-9]{2}):([0-9]{2}):([0-9]{2})(AM|PM)/).splice(1)
Upvotes: 0