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

Solution 1:

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

Solution 2:

function pad_with_zeroes(number, length) {

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

    return my_string;

}

Solution 3:

try these:

('0000' + number).slice(-4);

or

(number+'').padStart(4,'0');