I'm getting a date from a database that sometimes has spaces in the times (there isn't a way to clean up DB as I don't have control). I need to remove the spaces so I can format it to a Javascrpt date.
For example:
5 : 03 PM
As you can see, this is incorrect. I've looked at Moment.js and Regex to remove spaces around the colon, but not sure how that's done or if that's the proper way. Is there a way to remove this space?
Thanks all!
Only to delete the space around the colon, try the following; (where $1
refers to the first capture group, that is the only one (:)
)
a.replace(/\s*(:)\s*/, "$1");
or if you wish to simplify it further, without any capturing group;
a.replace(/\s*:\s*/, ":");
If you want to, you can actually parse that date string with Moment.js, you just need to include the spaces in your formatting string:
var time = moment('5 : 03 PM', 'h : m A');
Then you can format it however you want:
time.format('h:mmA'); // "5:30PM"
time.format('hh:mm A'); // "05:03 PM"
time.format('HH:mm'); // "17:03"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With