gpt4 book ai didi

Javascript - 匹配此数据表示的正则表达式

转载 作者:行者123 更新时间:2023-12-03 02:22:23 25 4
gpt4 key购买 nike

如何编写正确的正则表达式:

/Date(1518238800000)/ - matches

jdsjdsj - no match

2017/03/12 - no match

12 - no match

Date() - no match

/Date(1218238800000)/ - matches

到目前为止我所拥有的是:

var res = str.match(/Date(\d*)/g);

如何修改正则表达式以使其正常工作?

最佳答案

我假设您的字符串有点来自 .NET 序列化程序,如此处所述

How to parse ASP.NET JSON Date format with GWT

How to parse JSON to receive a Date object in JavaScript?

其中一个答案有您可能想要使用的恢复功能。

如果不是,那么正则表达式将需要转义括号:

var str = '{ "date": "/Date(1218238800000)/" }'
var re = /Date\((\d*)\)/g // escaping the () from the date and capture the number
res = re.exec(str);

console.log(res[1])

更多日期并创建日期对象:

var str = '{ "date1": "/Date(1218238800000)/", "date2": "/Date(1218248800000)/" }'
var re = /Date\((\d*)\)/g // escaping the () from the date and capture the number

while (res = re.exec(str)) {
var date = +res[1]; // convert
console.log(new Date(date))
}

关于Javascript - 匹配此数据表示的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49098136/

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