本文介绍了如何使用JavaScript从字符串中提取日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用javascript从字符串中提取日期?可以采用以下格式:

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

31.07.2014

31.07.2014

2014年7月31日

07.31.2014

2014.07.31
格式相同,但用空格或-或-
2014年7月31日
2014年7月31日
31-07 -2014

2014.07.31the same format but divided by spaces or / or -31 07 201431/07/201431-07-2014

字符串可能包含其他字符,例如

the string may contain other character like

Teen.Wolf.S04E06.Orphaned.28.07.2014 .HDTV

Teen.Wolf.S04E06.Orphaned.28.07.2014.HDTV

那么如何从这些类型的名称中提取日期。

so how to extract date from these type of name.

我想到了首先提取所有数字,然后比较是否大于12以确保它是月份或日期。
我对regEx(正则表达式)了解不多,因此,如果使用它,请解释一下谢谢

I thought of first extracting all the numbers and then comparing if it is greater than 12 to make sure it is month or date.I don't know much about regEx (Regular Expressions) so if it is used please explain a little thank you

推荐答案

可能使用正则表达式,例如

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 .

您可以拉出正则表达式的第一部分并进行检查,它与第二部分相同,除了4位和2位已被交换

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}/

这篇关于如何使用JavaScript从字符串中提取日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 23:13