在文本中查找日期
Find dates in text
我想在文档中查找日期。
并且return这个数组中的日期。
假设我有这段文字:
On the 03/09/2015 I am swiming in a pool, that was build on the 27-03-1994
现在我的代码应该 return ['03/09/2015','27-03-1994']
或者数组中的两个 Date 对象。
我的想法是用正则表达式解决这个问题,但是方法search()
只有return一个结果,而test()
我只能测试一个字符串!
你会如何尝试解决它? 特别是当你不知道日期的确切格式时?谢谢
您可以使用match()
with regex /\d{2}([\/.-])\d{2}\d{4}/g
var str = 'On the 03/09/2015 I am swiming in a pool, that was build on the 27-03-1994';
var res = str.match(/\d{2}([\/.-])\d{2}\d{4}/g);
document.getElementById('out').value = res;
<input id="out">
或者你可以在捕获组的帮助下做这样的事情
var str = 'On the 03/09/2015 I am swiming in a pool, that was build on the 27-03-1994';
var res = str.match(/\d{2}(\D)\d{2}\d{4}/g);
document.getElementById('out').value = res;
<input id="out">
我想在文档中查找日期。
并且return这个数组中的日期。
假设我有这段文字:
On the 03/09/2015 I am swiming in a pool, that was build on the 27-03-1994
现在我的代码应该 return ['03/09/2015','27-03-1994']
或者数组中的两个 Date 对象。
我的想法是用正则表达式解决这个问题,但是方法search()
只有return一个结果,而test()
我只能测试一个字符串!
你会如何尝试解决它? 特别是当你不知道日期的确切格式时?谢谢
您可以使用match()
with regex /\d{2}([\/.-])\d{2}\d{4}/g
var str = 'On the 03/09/2015 I am swiming in a pool, that was build on the 27-03-1994';
var res = str.match(/\d{2}([\/.-])\d{2}\d{4}/g);
document.getElementById('out').value = res;
<input id="out">
或者你可以在捕获组的帮助下做这样的事情
var str = 'On the 03/09/2015 I am swiming in a pool, that was build on the 27-03-1994';
var res = str.match(/\d{2}(\D)\d{2}\d{4}/g);
document.getElementById('out').value = res;
<input id="out">