javascript - 如何使用 JavaScript/Jquery 从字符串中获取所有日期和时间?

标签 javascript jquery regex datetime trim

我正在尝试使用 JS/Jquery 获取所有 DateTime 字段。

目前我正在尝试使用 Regex,但失败得很惨。

输入:

12345 User Name 9/10/2018 11:39:37 AM Valid Entry Place1 
12345 User Name 9/10/2018 12:48:43 PM Valid Exit Outside Place1 
12345 User Name 9/10/2018 1:00:44 PM Valid Entry Place1 
12345 User Name 9/10/2018 2:17:01 PM Valid Exit Outside Place1 
12345 User Name 9/10/2018 3:23:36 PM Valid Entry Place1 
12345 User Name 9/10/2018 3:25:56 PM Valid Entry Place1 
12345 User Name 9/10/2018 6:06:25 PM Valid Exit Outside Place1 
12345 User Name 9/10/2018 6:07:55 PM Valid Entry LC 
12345 User Name 9/10/2018 6:28:19 PM Valid Exit Outside LC 
12345 User Name 9/10/2018 6:30:06 PM Valid Entry Place1

预期输出:

9/10/2018 11:39:37 AM
9/10/2018 12:48:43 PM
9/10/2018 1:00:44 PM
9/10/2018 2:17:01 PM
9/10/2018 3:23:36 PM
9/10/2018 3:25:56 PM
9/10/2018 6:06:25 PM
9/10/2018 6:07:55 PM
9/10/2018 6:28:19 PM
9/10/2018 6:30:06 PM

当前逻辑:

function myFunction() {
    var str = document.getElementById("demo").innerHTML; 
    var txtIdAndName = str.replace(/[0-9]*\s[a-z,\s*]*/ig,"");
    var txtStatusAndPlace = txtIdAndName.replace(/[AM,PM]+\s[a-z,\s*]*/ig,"<br/>");
    document.getElementById("demo").innerHTML = txtStatusAndPlace;
}

如果我需要更多信息,请务必告诉我。

可以使用任何逻辑或方法来完成任务。

提前致谢

最佳答案

您可以将这些子串与

s.match(/\b\d{1,2}\/\d{1,2}\/\d{4}\s+\d{1,2}:\d{2}:\d{2}\s*[AP]M\b/g)

参见 regex demo

详情

  • \b - 单词边界
  • \d{1,2} - 1 位或 2 位数字,
  • \/ - 斜杠(因为正则表达式文字符号与 / 一起用作分隔符而被转义)
  • \d{1,2}\/\d{4} - 1 或 2 位数字,/ 然后是 4 位数字
  • \s+ - 1+ 个空格
  • \d{1,2}:\d{2}:\d{2} - (时间模式)1 或 2 位,:,2 位, : 和另外 2 位数字
  • \s* - 0+ 个空格
  • [AP] - AP
  • M - M 字符
  • \b - 单词边界。

JS 演示:

var s = "12345 User Name 9/10/2018 11:39:37 AM Valid Entry Place1 \n12345 User Name 9/10/2018 12:48:43 PM Valid Exit Outside Place1 \n12345 User Name 9/10/2018 1:00:44 PM Valid Entry Place1 \n12345 User Name 9/10/2018 2:17:01 PM Valid Exit Outside Place1 \n12345 User Name 9/10/2018 3:23:36 PM Valid Entry Place1 \n12345 User Name 9/10/2018 3:25:56 PM Valid Entry Place1 \n12345 User Name 9/10/2018 6:06:25 PM Valid Exit Outside Place1 \n12345 User Name 9/10/2018 6:07:55 PM Valid Entry LC \n12345 User Name 9/10/2018 6:28:19 PM Valid Exit Outside LC \n12345 User Name 9/10/2018 6:30:06 PM Valid Entry Place1";
var rx = /\b\d{1,2}\/\d{1,2}\/\d{4}\s+\d{1,2}:\d{2}:\d{2}\s*[AP]M\b/g;
document.body.innerHTML = "<pre>" + s.match(rx).join("<br/>") + "</pre>";

关于javascript - 如何使用 JavaScript/Jquery 从字符串中获取所有日期和时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52270679/

相关文章:

javascript - 在悬停时创建背景

javascript - 使用 JavaScript 从网站获取 JSON

jQuery循环插件交错/增量

javascript - 如何将字符串正确解析为onclick方法

javascript - 不被字母数字字符包围的单词的正则表达式

java - Matcher.replaceAll - 在 $,\in replacement String 上阻塞

javascript - 为什么liquidfun js说世界不存在

javascript - 您将如何在同一行中将 Math.abs 和 toLocaleString() 链接在一起?

javascript - 使用 JavaScript 打开第一个 Accordion 选项卡

regex - 使用正则表达式以任意顺序查找单词