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

后端 未结 11 858
轻奢々
轻奢々 2020-12-10 23:58
var number = 1310;

should be left alone.

var number = 120;

should be changed to \"0120\";

var num         


        
相关标签:
11条回答
  • 2020-12-11 00:26

    Use String.JS librairy function padLeft:

    S('123').padLeft(5, '0').s   --> 00123
    
    0 讨论(0)
  • 2020-12-11 00:30

    try these:

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

    or

    (number+'').padStart(4,'0');
    
    0 讨论(0)
  • 2020-12-11 00:32
    //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'
    
    0 讨论(0)
  • 2020-12-11 00:33

    Nate as the best way I found, it's just way too long to read. So I provide you with 3 simples solutions.

    1. So here's my simplification of Nate's answer.

    //number = 42
    "0000".substring(number.toString().length, 4) + number;
    

    2. Here's a solution that make it more reusable by using a function that takes the number and the desired length in parameters.

    function pad_with_zeroes(number, len) {
      var zeroes = "0".repeat(len);
      return zeroes.substring(number.toString().length, len) + number;
    }
    
    // Usage: pad_with_zeroes(42,4);
    // Returns "0042"
    

    3. Here's a third solution, extending the Number prototype.

    Number.prototype.toStringMinLen = function(len) {
      var zeroes = "0".repeat(len);
      return zeroes.substring(self.toString().length, len) + self;
    }
    
    //Usage: tmp=42; tmp.toStringMinLen(4)
    
    0 讨论(0)
  • 2020-12-11 00:34

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

    0 讨论(0)
提交回复
热议问题