Skip to content Skip to sidebar Skip to footer

Splitting Numbers And Letters In String Which Contains Both

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',

Solution 1:

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

Solution 2:

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)

Solution 3:

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.

Post a Comment for "Splitting Numbers And Letters In String Which Contains Both"