2

I have the following time format 2h 34m 22s and I'm parsing it as 02:34:22 using this code:

const splitterArray = '2h 34m 22s'.split(' ');

let h = '00', m = '00', s = '00';

splitterArray.forEach(val => {
    if (val.includes('h')) {
        h = val.replace('h', '');
    } else if (val.includes('m')) {
        m = val.replace('m', '');
    }
    else if (val.includes('s')) {
        s = val.replace('s', '');
    }
});

console.log(`${h}:${m}:${s}`);

This also handles the case when there's only minutes and seconds, or only hours and seconds or only hours and minutes.

Just checking if there's a better way to do it like a library or so (maybe to accept days too).

2
  • Is the time string always in that format or do you have it as a date string / object at some point prior to it being converted to this '2h 34m 22s' format? If you have the necessary date string / object, you could format using date-fns or momentjs Commented Apr 19, 2021 at 18:33
  • @ElbertBae always like this .. could include days too (2d 22h 33m 12s). Commented Apr 19, 2021 at 18:35

2 Answers 2

2

You could match in wanted order and get the result with colons.

function convert(string) {
    return Array
        .from('hms', p => (string.match(new RegExp(`\\d+(?=${p})`))?.[0] || '') .padStart(2, '0'))
        .join(':');
}

console.log(convert('2h 34m 22s'));

Sign up to request clarification or add additional context in comments.

Comments

0

I suggest using the moment library. it has plenty of examples and documentation for all of your time formatting and parsing needs:

https://momentjs.com/

1 Comment

Momentjs has been deprecated. See momentjs.com/docs

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.