Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

People also ask

How do you put a zero at the beginning of a string?

Use the padStart() method to add leading zeros to a string. The method allows us to pad the current string with zeros to a specified target length and returns the result.

How do you add leading zeros to numbers or text with uneven lengths JS?

To pad a number with leading zeros convert the number to a string and call the padStart() method. The padStart method allows you to add leading zeros to the start of the string until it reaches the specified target length.


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

function pad_with_zeroes(number, length) {

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

    return my_string;

}

try these:

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

or

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

Here's another way. Comes from something I did that needs to be done thousands of times on a page load. It's pretty CPU efficient to hard code a string of zeroes one time, and chop as many as you need for the pad as many times as needed. I do really like the power of 10 method -- that's pretty flexible.

Anyway, this is as efficient as I could come up with:

For the original question, CHOOSE ONE of the cases...

var number = 1310;
var number = 120;
var number = 10;
var number = 7;

then

// only needs to happen once 
var zeroString = "00000";

// one assignment gets the padded number
var paddedNum = zeroString.substring((number + "").length, 4) + bareNum;

//output
alert("The padded number string is: " + paddedNum);

Of course you still need to validate the input. Because this ONLY works reliably under the following conditions:

  • Number of zeroes in the zeroString is desired_length + 1
  • Number of digits in your starting number is less than or equal to your desired length

Backstory:

I have a case that needs a fixed length (14 digit) zero-padded number. I wanted to see how basic I could make this. It's run tens of thousands of times on a page load, so efficiency matters. It's not quite re-usable as-is, and it's a bit inelegant. Except that it is very very simple.

For desired n digits padded string, this method requires a string of (at least) n+1 zeroes. Index 0 is the first character in the string, which won't ever be used, so really, it could be anything.

Note also that string.substring() is different from string.substr()!

var bareNum = 42 + '';  
var zeroString = "000000000000000";
var paddedNum = zeroString.substring(bareNumber.length, 14) + bareNum

This pulls zeroes from zeroString starting at the position matching the length of the string, and continues to get zeroes to the necessary length of 14. As long as that "14" in the third line is a lower integer than the number of characters in zeroString, it will work.


function pad(n, len) {
  return (new Array(len + 1).join('0') + n).slice(-len);
}

might not work in old IE versions.


//to: 0 - to left, 1 - to right
String.prototype.pad = function(_char, len, to) {
    if (!this || !_char || this.length >= len) {
        return this;
    }
    to = to || 0;

    var ret = this;

    var max = (len - this.length)/_char.length + 1;
    while (--max) {
        ret = (to) ? ret + _char : _char + ret;
    }

    return ret;
};

Usage:

someString.pad(neededChars, neededLength)

Example:

'332'.pad('0', 6); //'000332'
'332'.pad('0', 6, 1); //'332000'