gpt4 book ai didi

javascript - 用于检查文本日期格式的正则表达式未按预期工作

转载 作者:行者123 更新时间:2023-12-01 00:28:57 24 4
gpt4 key购买 nike

我有一个函数可以检查 html 页面的一部分结构。我基本上想确定 div 元素是否以文本/内容中的日期开头。如果是这样,那么我想更改 HTML(但这超出了这个问题的范围。

我的控制如下:

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)?以防万一事情就这么简单。

关于javascript - 用于检查文本日期格式的正则表达式未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58736667/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com