javascripttimecodes

Transform string to timecode pattern?


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

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

Solution

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