Javascript adding zeros to the beginning of a string (max length 4 chars)

function pad_with_zeroes(number, length) {

    var my_string = '' + number;
    while (my_string.length < length) {
        my_string = '0' + my_string;
    }

    return my_string;

}

In all modern browsers you can use

numberStr.padStart(4, "0");

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart

function zeroPad(num) {
  return num.toString().padStart(4, "0");
}

var numbers = [1310, 120, 10, 7];

numbers.forEach(
  function(num) {        
    var paddedNum = zeroPad(num);

    console.log(paddedNum);
  }
);

Tags:

Javascript