3 examples of input:
"13-4h50m2s"
"13-4h2s"
"13-50m"
Preferred code:
const [hours = 0, minutes = 0, seconds = 0] = input.match(some_regexp)
Wanted output {hours,minutes,seconds} for the 3 examples:
{hours: 4, minutes: 50, seconds: 2}
{hours: 4, minutes: 0, seconds: 2}
{hours: 0, minutes: 50, seconds: 0}
Regex I’ve tried: /(\d+)?[a-z](\d+)?[a-z]?(\d+)?[a-z]?/
. But then the second example doesn’t work.
EDIT
Actually, input can be expected to be sorted in the right order (h,m,s).
And it doesn’t matter if the values are stored as strings or numbers.
This should answer your question:
Output:
Notes:
labelMap
maps from your input unit to the desired output object key/(\d+)([hms])/g
You could match the digits and suffix, and then use
Object.fromEntries
to turn that result into an object. Use an object initialiser with spread syntax to get 0 for non-populated properties:NB/ This reuses the single letters h, m, s as property names.