How to extract date from string using javascript

后端 未结 5 1460
轮回少年
轮回少年 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:16

    probably use a regex like

    /(\d{4}([.\-/ ])\d{2}\2\d{2}|\d{2}([.\-/ ])\d{2}\3\d{4})/
    
    \d - a digit (equivilant to character class [0-9]
    {n} - match n characters
    [.\-/ ] - character class matches a single . - / or space (- needs to be escaped because it indicates a range in a character class
    \n - a backreference matches the nth match so / will match another / and not a -, /, space or .
    

    you can pull out the first part of the regex and inspect it, it is the same as the second part, except the 4 digits and 2 digits have been swapped

    /\d{4}([.\-/ ])\d{2}\1\d{2}/
    

提交回复
热议问题