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

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

提交回复
热议问题