Is there a JavaScript function that can pad a stri

2018-12-31 13:14发布

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:

String.prototype.pad = function(l, s, t){
    return s || (s = " "), (l -= this.length) > 0 ? (s = new Array(Math.ceil(l / s.length)
        + 1).join(s)).substr(0, t = !t ? l : t == 1 ? 0 : Math.ceil(l / 2))
        + this + s.substr(0, l - t) : this;
};

Example:

<script type="text/javascript">
//<![CDATA[

var s = "Jonas";
document.write(
    '<h2>S = '.bold(), s, "</h2>",
    'S.pad(20, "[]", 0) = '.bold(), s.pad(20, "[]", 0), "<br />",
    'S.pad(20, "[====]", 1) = '.bold(), s.pad(20, "[====]", 1), "<br />",
    'S.pad(20, "~", 2) = '.bold(), s.pad(20, "~", 2)
);

//]]>
</script>

But I have no idea what the heck it is doing and it doesn't seem to work for me.

30条回答
伤终究还是伤i
2楼-- · 2018-12-31 13:29
  1. Never insert data somewhere (especially not at beginning, like str = pad + str;), since the data will be reallocated everytime. Append always at end!
  2. Don't pad your string in the loop. Leave it alone and build your pad string first. In the end concatenate it with your main string.
  3. Don't assign padding string each time (like str += pad;). It is much faster to append the padding string to itself and extract first x-chars (the parser can do this efficiently if you extract from first char). This is exponential growth, which means that it wastes some memory temporarily (you should not do this with extremely huge texts).

if (!String.prototype.lpad) {
    String.prototype.lpad = function(pad, len) {
        while (pad.length < len) {
            pad += pad;
        }
        return pad.substr(0, len-this.length) + this;
    }
}

if (!String.prototype.rpad) {
    String.prototype.rpad = function(pad, len) {
        while (pad.length < len) {
            pad += pad;
        }
        return this + pad.substr(0, len-this.length);
    }
}

查看更多
泪湿衣
3楼-- · 2018-12-31 13:30

Using the ECMAScript 6 method String#repeat, a pad function is as simple as:

String.prototype.padLeft = function(char, length) { 
    return char.repeat(Math.max(0, length - this.length)) + this;
}

String#repeat is currently supported in Firefox and Chrome only. for other implementation, one might consider the following simple polyfill:

String.prototype.repeat = String.prototype.repeat || function(n){ 
    return n<=1 ? this : (this + this.repeat(n-1)); 
}
查看更多
不流泪的眼
4楼-- · 2018-12-31 13:31

Here's a simple function that I use.

var pad=function(num,field){
    var n = '' + num;
    var w = n.length;
    var l = field.length;
    var pad = w < l ? l-w : 0;
    return field.substr(0,pad) + n;
};

For example:

pad    (20,'     ');    //   20
pad   (321,'     ');    //  321
pad (12345,'     ');    //12345
pad (   15,'00000');    //00015
pad (  999,'*****');    //**999
pad ('cat','_____');    //__cat  
查看更多
初与友歌
5楼-- · 2018-12-31 13:33
1. function
var _padLeft = function(paddingString, width, replacementChar) {
    return paddingString.length >= width ? paddingString : _padLeft(replacementChar + paddingString, width, replacementChar || ' ');
};

2. String prototype
String.prototype.padLeft = function(width, replacementChar) {
        return this.length >= width ? this.toString() : (replacementChar + this).padLeft(width, replacementChar || ' ');
};

3. slice
('00000' + paddingString).slice(-5)
查看更多
孤独总比滥情好
6楼-- · 2018-12-31 13:34

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);
查看更多
登录 后发表回答