How to extract date from string using javascript

后端 未结 5 1575
轮回少年
轮回少年 2021-01-21 11:35

How does one extract a date from a string using javascript? It can be in the following formats:

31.07.2014

07.31.2014

2014.07.31 the same format but divi

5条回答
  •  难免孤独
    2021-01-21 12:11

    I think you can use regex for this. The main three expressions that you need are the following:

    [0-9]{4} // year
    (0[1-9]|1[0-2]) // month
    (0[1-9]|[1-2][0-9]|3[0-1]) // day
    

    You can combine these to fit the formats you mentioned, for example, to match "31.07.2014":

    (0[1-9]|[1-2][0-9]|3[0-1])\.(0[1-9]|1[0-2])\.[0-9]{4}
    

    Or "31/07/2014":

    (0[1-9]|[1-2][0-9]|3[0-1])\/(0[1-9]|1[0-2])\/[0-9]{4}
    

    You can decide which formats you need and create one regex expression separating the formats with the OR operator |.

提交回复
热议问题