0

How can I get zeroes into my strings with the following results (a few examples):

  • 1 => 01
  • 01.0 => 01.00
  • 1.0.01.00 => 01.00.01.00
  • 1.0.0.0 => 01:00:00:00
  • 10.0.10.0 => 10:00:10:00

This is what I've come up with so far but it doesn't give me what I want. Thanks for help!

tc = tc.replace('.', ':');
tc = tc.replace(',', ':');
tc = tc.replace(/(:|^)(\d)(?=:|$)/g, "$10$2");
gyre
  • 16,369
  • 3
  • 37
  • 47
SeaBass
  • 1,584
  • 4
  • 20
  • 46

1 Answers1

0

Prepend 0 to all single digits surrounded by word boundaries (\b), and then replace every comma and period with a colon using the character set [.,]. Don't forget to use the global (g) flag on each regular expression so that every occurrence of the target pattern is replaced, not just the first one.

function timecode (s) {
  return s.replace(/\b(\d)\b/g, '0$1').replace(/[.,]/g, ':')
}

console.log(timecode('1') === '01')
console.log(timecode('01.0') === '01:00')
console.log(timecode('1.0.01.00') === '01:00:01:00')
console.log(timecode('1.0.0.0') === '01:00:00:00')
console.log(timecode('10.0.10.0') === '10:00:10:00')
gyre
  • 16,369
  • 3
  • 37
  • 47