0

I'm using clockpicker to collect user input that will give me a digital timestamp in a string.

For example:

02:15

I would like to keep that as is in the database but in my view print it as, using this example:

2h 15m 

Unnecessary zero's removed, spaced and with added "h" for "hours" and "m" for "minutes". Also if no hours would be specified I'd prefer only getting the minutes, and vice versa if no minutes is specified.

All examples I seem to find is about converting a complete timestamp using "Date" function in JavaScript. I don't seem to be able to use that with just this value and I'm terrible with regex.

I would like to find an elegant way, perhaps a one line regex to replace it before rendering my view. I'd prefer not using any additional libraries.

Any help appreciated!

1 Answers1

0

I seem to have managed anyway. It's not as pretty as I would like it to be, but it works, and It's technically a one line regex.

  t = "00:05";
  t2 = "01:00";
  t3 = "12:10";
  t4 = "02:02";

  const replaceTime = (myString) => {
    myString = myString.replace(/0?([1-9]{0,}[0-9]):0?([1-9]{0,}[0-9])/g, '$1h $2m').replace(/\s0m/g, '').replace(/0h\s/g, '');
    return myString;
  }

  console.log(replaceTime(t));
  console.log(replaceTime(t2));
  console.log(replaceTime(t3));
  console.log(replaceTime(t4));

returns:

5m
1h
12h 10m
2h 2m