String pad and unpad - Node.js String

Node.js examples for String:Padding

Description

String pad and unpad

Demo Code


String.prototype.pad = function(l, r) {
    if (r === null) {
        r = l//from  w  w w.j av a2 s .c  o  m
        if (!(this.substr(0, 2) == "0x" || /^\d+$/.test(this)))
            l = 0
    }
    var ret = this.bin();
    while (ret.length < l)
        ret = "\0" + ret
    while (ret.length < r)
        ret = ret + "\0"
    return ret;
}

String.prototype.unpad = function() {
    var i = this.length;
    while (i && this[i - 1] == "\0")
        --i
    return this.substr(0, i)
}

Related Tutorials