[英]regular expression to check text for date format not working as expected
我有一个 function 来检查我的 html 页面的一部分的结构。 我基本上想确定 div 元素是否以文本/内容中的日期开头。 如果是这样,那么我想更改 HTML (但对于这个问题,这超出了 scope 的范围。
我的控制如下:
function isDate(_date){
const _regExp = new RegExp('^(-?(?:[1-9][0-9]*)?[0-9]{4})-(1[0-2]|0[1-9])-(3[01]|0[1-9]|[12][0-9]) (2[0-3]|[01][0-9]):([0-5][0-9])?$');
return _regExp.test(_date);
}
$(function() {
var entries = $("div.histEntry");
console.log('2018-08-01 18:30 is Date? ' + isDate('2018-08-01 18:30'));
console.log('hungry like a wolf is Date? ' + isDate('hungry like a wolf'));
$("div.histEntry").each(function( index, value ) {
console.log('content of div: ' + $(this).text());
console.log('text to check: ' + $(value).text().substring(0, 17));
console.log('is Date?: ' + isDate($(value).text().substring(0, 17)));
});
});
这是我在控制台中返回的一个片段:
2018-08-01 18:30 is Date? true
hungry like a wolf is Date? false
content of div:
2019-04-12 13:55 John Doe/Web/ACME created this document
text to check:
2019-04-12 13:55
is Date?: false
content of div:
2019-04-15 14:03 Office Manager changed from Jim Joe to Billy Boy
text to check:
2019-04-15 14:03
is Date?: false
content of div:
Mikael commented this document
text to check:
Mikael commented
is Date?: false
为什么 2018-08-01 18:30 被视为日期而 2019-04-15 14:03 不是?
也许您正在测试一个末尾包含空格的字符串。 您是否尝试过检查$(value).text().substring(0, 16)
? 以防万一就这么简单。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.