Search code examples
javascriptjqueryregexdatetimetrim

How to fetch all dates and time from string using JavaScript/Jquery?


I'm trying to fetch all DateTime fields using JS/Jquery.

Currently I'm trying it with Regex, but failing miserably.

INPUT:

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

EXPECTED OUTPUT:

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

CURRENT LOGIC:

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;
}

Please do let me know if any more info is needed form my end.

Can use any Logic or method to achieve the task.

Thanks in advance


Solution

  • You may match these substrings with

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

    See the regex demo

    Details

    • \b - a word boundary
    • \d{1,2} - 1 or 2 digits,
    • \/ - a slash (escaped since a regex literal notation is used with / as delimiters)
    • \d{1,2}\/\d{4} - 1 or 2 digits, / and then 4 digits
    • \s+ - 1+ whitespaces
    • \d{1,2}:\d{2}:\d{2} - (time pattern) 1 or 2 digits, :, 2 digits, : and another 2 digits
    • \s* - 0+ whitespaces
    • [AP] - A or P
    • M - an M char
    • \b - a word boundary.

    JS demo:

    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>";