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

前端 未结 30 1646
悲哀的现实
悲哀的现实 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 "
    

提交回复
热议问题