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

前端 未结 30 1668
悲哀的现实
悲哀的现实 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 08:58

    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 );
    });
    

提交回复
热议问题