Parsing string into Time format JavaScript

Viewed 126

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 Answers

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'));

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/

Related