我想在文档中查找日期。
并以数组形式返回此日期。
假设我有以下文本:
On the 03/09/2015 I am swiming in a pool, that was build on the 27-03-1994
现在我的代码应该返回 ['03/09/2015','27-03-1994']
或者只是数组中的两个 Date 对象。
我的想法是用正则表达式解决这个问题,但是方法search()
只返回一个结果并且 test()
我只能测试一个字符串!
您将如何尝试解决它?特别是当您不知道日期的确切格式时?谢谢
最佳答案
您可以使用match()
与正则表达式 /\d{2}([\/.-])\d{2}\1\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}\1\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}\1\d{4}/g);
document.getElementById('out').value = res;
<input id="out">
关于javascript - 查找文本中的日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32949649/