1

i am trying to write some Javascript for a Google Tag Manager variable that will return the number of minutes currently spent on a web page and then send that through to Google Analytics as an event. Currently, the code below works, but it is returning anything below 10 minutes as a single digit, and anything below 100 minutes as double digits. I'd like to add leading zeros so that the minutes number is always 3 digits. I want to do this so I can sort events by minutes in GA, and have them sort in the correct time order. For example, I want one minute to be in the format "001m 0s" and twelve minutes to be in the format "012m 0s". Make sense? Here is the code I have currently:

function() {
var elapsed = {{timerEventNumber}} * {{timerInterval}} / 1000;
var min = Math.floor(elapsed/60);
var sec = elapsed % 60;
return min + 'm ' + sec + 's';
}

Thanks, Mark

Mark H
  • 13
  • 2

1 Answers1

3

Add the leading zeros, and create a substring from the last three characters of the string.

return ('00' + min).substr(-3) + 'm' + sec + 's';

String.prototype.substr()

Teemu
  • 22,918
  • 7
  • 53
  • 106