Is there a JavaScript function that can pad a string to get to a determined length?

前端 未结 30 1279
悲哀的现实
悲哀的现实 2020-11-22 08:28

I am in need of a JavaScript function which can take a value and pad it to a given length (I need spaces, but anything would do). I found this:

Code:

相关标签:
30条回答
  • 2020-11-22 09:20
    /**************************************************************************************************
    Pad a string to pad_length fillig it with pad_char.
    By default the function performs a left pad, unless pad_right is set to true.
    
    If the value of pad_length is negative, less than, or equal to the length of the input string, no padding takes place.
    **************************************************************************************************/
    if(!String.prototype.pad)
    String.prototype.pad = function(pad_char, pad_length, pad_right) 
    {
       var result = this;
       if( (typeof pad_char === 'string') && (pad_char.length === 1) && (pad_length > this.length) )
       {
          var padding = new Array(pad_length - this.length + 1).join(pad_char); //thanks to http://stackoverflow.com/questions/202605/repeat-string-javascript/2433358#2433358
          result = (pad_right ? result + padding : padding + result);
       }
       return result;
    }
    

    And then you can do:

    alert( "3".pad("0", 3) ); //shows "003"
    alert( "hi".pad(" ", 3) ); //shows " hi"
    alert( "hi".pad(" ", 3, true) ); //shows "hi "
    
    0 讨论(0)
  • 2020-11-22 09:21

    The key trick in both those solutions is to create an array instance with a given size (one more than the desired length), and then to immediately call the join() method to make a string. The join() method is passed the padding string (spaces probably). Since the array is empty, the empty cells will be rendered as empty strings during the process of joining the array into one result string, and only the padding will remain. It's a really nice technique.

    0 讨论(0)
  • 2020-11-22 09:22

    yet another take at with combination of a couple solutions

    /**
     * pad string on left
     * @param {number} number of digits to pad, default is 2
     * @param {string} string to use for padding, default is '0' *
     * @returns {string} padded string
     */
    String.prototype.paddingLeft = function (b,c) {
        if (this.length > (b||2))
            return this+'';
      return (this||c||0)+'',b=new Array((++b||3)-this.length).join(c||0),b+this
    };
    
    /**
     * pad string on right
     * @param {number} number of digits to pad, default is 2
     * @param {string} string to use for padding, default is '0' *
     * @returns {string} padded string
     */
    String.prototype.paddingRight = function (b,c) {
      if (this.length > (b||2))
            return this+'';
      return (this||c||0)+'',b=new Array((++b||3)-this.length).join(c||0),this+b
    };    
    
    0 讨论(0)
  • 2020-11-22 09:24

    Here is a simple answer in basically one line of code.

    var value = 35 // the numerical value
    var x = 5 // the minimum length of the string
    
    var padded = ("00000" + value).substr(-x);
    

    Make sure the number of characters in you padding, zeros here, is at least as many as your intended minimum length. So really, to put it into one line, to get a result of "00035" in this case is:

    var padded = ("00000" + 35).substr(-5);
    
    0 讨论(0)
  • 2020-11-22 09:24

    A friend asked about using a JavaScript function to pad left. It turned into a little bit of an endeavor between some of us in chat to code golf it. This was the result:

    function l(p,t,v){
        v+="";return v.length>=t?v:l(p,t,p+v); 
    }
    

    It ensures that the value to be padded is a string, and then if it isn't the length of the total desired length it will pad it once and then recurse. Here is what it looks like with more logical naming and structure

    function padLeft(pad, totalLength, value){
        value = value.toString();
    
        if( value.length >= totalLength ){
            return value;
        }else{
            return padLeft(pad, totalLength, pad + value);
        }
    }
    

    The example we were using was to ensure that numbers were padded with 0 to the left to make a max length of 6. Here is an example set:

    function l(p,t,v){v+="";return v.length>=t?v:l(p,t,p+v);}
    
    var vals = [6451,123,466750];
    
    var pad = l(0,6,vals[0]);// pad with 0's, max length 6
    
    var pads = vals.map(function(i){ return l(0,6,i) });
    
    document.write(pads.join("<br />"));

    0 讨论(0)
  • 2020-11-22 09:25

    I found this solution here and this is for me much much simpler:

    var n = 123
    
    String("00000" + n).slice(-5); // returns 00123
    ("00000" + n).slice(-5); // returns 00123
    ("     " + n).slice(-5); // returns "  123" (with two spaces)
    

    And here I made an extension to the string object:

    String.prototype.paddingLeft = function (paddingValue) {
       return String(paddingValue + this).slice(-paddingValue.length);
    };
    

    An example to use it:

    function getFormattedTime(date) {
      var hours = date.getHours();
      var minutes = date.getMinutes();
    
      hours = hours.toString().paddingLeft("00");
      minutes = minutes.toString().paddingLeft("00");
    
      return "{0}:{1}".format(hours, minutes);
    };
    
    String.prototype.format = function () {
        var args = arguments;
        return this.replace(/{(\d+)}/g, function (match, number) {
            return typeof args[number] != 'undefined' ? args[number] : match;
        });
    };
    

    This will return a time in the format "15:30"

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