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条回答
刘海飞了
2楼-- · 2018-12-31 13:35

Taking up Samuel's ideas, upward here. And remember an old SQL script, I tried with this:

a=1234;
'0000'.slice(a.toString().length)+a;

It works in all the cases I could imagine:

a=     1 result  0001
a=    12 result  0012
a=   123 result  0123
a=  1234 result  1234
a= 12345 result 12345
a=  '12' result  0012
查看更多
美炸的是我
3楼-- · 2018-12-31 13:36

http://www.webtoolkit.info/javascript_pad.html

/**
*
*  Javascript string pad
*  http://www.webtoolkit.info/
*
**/

var STR_PAD_LEFT = 1;
var STR_PAD_RIGHT = 2;
var STR_PAD_BOTH = 3;

function pad(str, len, pad, dir) {

    if (typeof(len) == "undefined") { var len = 0; }
    if (typeof(pad) == "undefined") { var pad = ' '; }
    if (typeof(dir) == "undefined") { var dir = STR_PAD_RIGHT; }

    if (len + 1 >= str.length) {

        switch (dir){

            case STR_PAD_LEFT:
                str = Array(len + 1 - str.length).join(pad) + str;
            break;

            case STR_PAD_BOTH:
                var padlen = len - str.length;
                var right = Math.ceil( padlen / 2 );
                var left = padlen - right;
                str = Array(left+1).join(pad) + str + Array(right+1).join(pad);
            break;

            default:
                str = str + Array(len + 1 - str.length).join(pad);
            break;

        } // switch

    }

    return str;

}

It's a lot more readable.

查看更多
闭嘴吧你
4楼-- · 2018-12-31 13:39
/**************************************************************************************************
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 "
查看更多
还给你的自由
5楼-- · 2018-12-31 13:41

Here's a recursive approach to it.

function pad(width, string, padding) { 
  return (width <= string.length) ? string : pad(width, padding + string, padding)
}

An example...

pad(5, 'hi', '0')
=> "000hi"
查看更多
有味是清欢
6楼-- · 2018-12-31 13:41

es7 is just drafts and proposals right now, but if you wanted to track compatibility with the spec, your pad functions need:

  1. Multi-character pad support.
  2. Don't truncate the input string
  3. Pad defaults to space

From my polyfill library, but apply your own due diligence for prototype extensions.

// Tests
'hello'.lpad(4) === 'hello'
'hello'.rpad(4) === 'hello'
'hello'.lpad(10) === '     hello'
'hello'.rpad(10) === 'hello     '
'hello'.lpad(10, '1234') === '41234hello'
'hello'.rpad(10, '1234') === 'hello12341'

String.prototype.lpad || (String.prototype.lpad = function( length, pad )
{
    if( length < this.length ) return this;

    pad = pad || ' ';
    let str = this;

    while( str.length < length )
    {
        str = pad + str;
    }

    return str.substr( -length );
});

String.prototype.rpad || (String.prototype.rpad = function( length, pad )
{
    if( length < this.length ) return this;

    pad = pad || ' ';
    let str = this;

    while( str.length < length )
    {
        str += pad;
    }

    return str.substr( 0, length );
});
查看更多
明月照影归
7楼-- · 2018-12-31 13:42

A short way:

(x=>(new Array(int-x.length+1)).join(char)+x)(String)

Example:

(x=>(new Array(6-x.length+1)).join("0")+x)("1234")

return: "001234"

查看更多
登录 后发表回答