Adding extra zeros in front of a number using jQuery?

后端 未结 14 1183
粉色の甜心
粉色の甜心 2020-11-30 02:45

I have file that are uploaded which are formatted like so

MR 1

MR 2

MR 100

MR 200

MR 300

14条回答
  •  时光说笑
    2020-11-30 03:27

    Note: see Update 2 if you are using latest ECMAScript...


    Here a solution I liked for its simplicity from an answer to a similar question:

    var n = 123
    
    String('00000' + n).slice(-5); // returns 00123
    ('00000' + n).slice(-5);       // returns 00123
    

    UPDATE

    As @RWC suggested you can wrap this of course nicely in a generic function like this:

    function leftPad(value, length) { 
        return ('0'.repeat(length) + value).slice(-length); 
    }
    
    leftPad(123, 5); // returns 00123
    

    And for those who don't like the slice:

    function leftPad(value, length) {
        value = String(value);
        length = length - value.length;
        return ('0'.repeat(length) + value)
    }
    

    But if performance matters I recommend reading through the linked answer before choosing one of the solutions suggested.

    UPDATE 2

    In ES6 the String class now comes with a inbuilt padStart method which adds leading characters to a string. Check MDN here for reference on String.prototype.padStart(). And there is also a padEnd method for ending characters.

    So with ES6 it became as simple as:

    var n = 123;
    n.padStart(5, '0'); // returns 00123
    

提交回复
热议问题