Separating numbers and letters in a string containing both

I am trying to split the following (or similar) line "08-27-2015 07:25:00 AM". I am currently using

var parts = date.split(/[^0-9a-zA-Z]+/g); 

The result is

 ["02", "27", "2012", "03", "25", "00AM"] 

The problem is with the 00AM part. I want to be shared too. Thus, the ideal result would be:

 ["02", "27", "2012", "03", "25", "00", "AM"] 
+6
source share
4 answers

If you are looking for a sequence of letters or numbers, but not a mixed sequence, you can do this ...

 "08-27-2015 07:25:00AM".match(/[a-zA-Z]+|[0-9]+/g) 

as a result...

 ["08", "27", "2015", "07", "25", "00", "AM"] 

On either side of | we have a sequence of one or more letters and a sequence of one or more numbers. Therefore, when he meets a letter, he will collect all the continuous letters until he reaches the letter in which he collects all adjacent numbers, etc.

Any other character simply does not match, so it does not become part of the result.

+20
source
 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(/([az]+)/i, " $1 ").split(/[^0-9a-z]+/ig); 
+1
source

If the date is always in this 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)

0
source

I would use a date library to parse the fields you want. This way you can handle multiple formats and not worry about parsing regular expressions. While DateJS is a bit dated, it is great for parsing.

0
source

Source: https://habr.com/ru/post/910937/


All Articles