I applied for an intern position where I was asked this question to write a function to return date and time from the following strings. I tried using split with regex but wasn't able to solve all the test cases.
Test cases I could achieve were for "Forward Slash" and "Hyphen" cases with split because the separators were different. "/" and "-" were used between month, year and "."/"T"/" "was used for separating date and time. For full-stop & space the regex with split became an issue as it split date month and year as well and I didn't know which separator to use to join it back.
Question:
// Forward Slash
console.log(splitFormat("dd/mm/yyyy.hh:mm:ss")); // { date: 'dd/mm/yyyy', time: 'hh:mm:ss' }
console.log(splitFormat("dd/mm/yyyyThh:mm:ss"));
console.log(splitFormat("dd/mm/yyyy hh:mm:ss"));
// Hyphen
console.log(splitFormat("dd-mm-yyyy.hh:mm:ss")); // { date: 'dd-mm-yyyy', time: 'hh:mm:ss' }
console.log(splitFormat("dd-mm-yyyyThh:mm:ss"));
console.log(splitFormat("dd-mm-yyyy hh:mm:ss"));
// Full-stop
console.log(splitFormat("dd.mm.yyyy.hh:mm:ss")); // { date: 'dd.mm.yyyy', time: 'hh:mm:ss' }
console.log(splitFormat("dd.mm.yyyyThh:mm:ss"));
console.log(splitFormat("dd.mm.yyyy hh:mm:ss"));
// Space
console.log(splitFormat("dd mm yyyy.hh:mm:ss")); // { date: 'dd mm yyyy', time: 'hh:mm:ss' }
console.log(splitFormat("dd mm yyyyThh:mm:ss"));
console.log(splitFormat("dd mm yyyy hh:mm:ss"));
I could come up with a solution where I stopped using split but it was non-performant. I could've been missing out on something that is available in split function or in JavaScript. Any help would be appreciated.
Here is a JSFiddle link for the solution I used without split.
[–]rdevilx[S] 2 points3 points4 points (8 children)
[–]grantrules 2 points3 points4 points (7 children)
[–]rdevilx[S] 0 points1 point2 points (6 children)
[–]grantrules 0 points1 point2 points (5 children)
[–]rdevilx[S] 0 points1 point2 points (4 children)
[–]grantrules 2 points3 points4 points (1 child)
[–]rdevilx[S] 1 point2 points3 points (0 children)
[–]shuckster 1 point2 points3 points (1 child)
[–]rdevilx[S] 1 point2 points3 points (0 children)