Nodejs String Padding Left lpad(pad, length)

Here you can find the source of lpad(pad, length)

Method Source Code

// we need a function to fill zeros in numbers less than
// 10. I could do the following:

function fill(num) {
    return (num == 10 ? '' : '0') + num;
}

// but hey, lpad should have been a function in String
// object IMO. so let's get a bit more adventurous.
String.prototype.lpad = function(pad, length) {
    var s = this;
    while (s.length < length) {
        s = pad + s;//from   w ww .  j a  va  2  s .co m
    }
    
    return s;
}

require('net').createServer(function (socket) {
    var date = new Date();
    socket.end(
        date.getFullYear() + '-' +
        (date.getMonth() + 1).toString().lpad('0', 2) + '-' +
        date.getDate().toString().lpad('0', 2) + ' ' +
        date.getHours().toString().lpad('0', 2) + ':' +
        date.getMinutes().toString().lpad('0', 2) + '\n');
}).listen(Number(process.argv[2]));

Related

  1. lpad(l)
    String.prototype.lpad = function(l) {
      var s = this;
      while (s.length < l) { s = "0"+s; }
      return s;
    
  2. lpad(len, padstr)
    String.prototype.lpad = function(len, padstr) {
      return Array(len + 1 - this.length).join(padstr) + this;
    };
    String.prototype.rpad = function(len, padstr) {
      return this + Array(len + 1 - this.length).join(padstr);
    };
    
  3. lpad(len, s)
    String.prototype.lpad = function(len, s) {   
        var a = new Array(this);   
        var n = (len - this.length);   
        for ( var i = 0; i < n; i++) {   
            a.unshift(s);   
        return a.join("");   
    };
    
  4. lpad(length, padString)
    String.prototype.lpad = function(length, padString){
        var str = this;
        while (str.length < length)
            str = padString + str;
        return str;
    };
    
  5. lpad(pSize, pCharPad)
    String.prototype.lpad = function(pSize, pCharPad)
      var str = this;
      var dif = pSize - str.length;
      var ch = String(pCharPad).charAt(0);
      for (; dif>0; dif--) str = ch + str;
      return (str);
    
  6. lpad(padLength, padString)
    String.prototype.lpad = function(padLength, padString){
        var s = this;
        while(s.length < padLength)
            s = padString + s;
        return s;
    
  7. lpad(padString, length)
    String.prototype.lpad = function(padString, length) {
      var str = this;
      while (str.length < length)
          str = padString + str;
      return str;
    
  8. lpad(padString, length)
    String.prototype.lpad = function(padString, length) {
      var str = this;
        while (str.length < length)
            str = padString + str;
        return str;
    
  9. lpad(padString, length)
    String.prototype.lpad = function(padString, length) {
        var str = this;
        while (str.length < length)
            str = padString + str;
        return str;