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

前端 未结 30 1298
悲哀的现实
悲哀的现实 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

    padding string has been inplemented in new javascript version.

    str.padStart(targetLength [, padString])

    https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Objetos_globales/String/padStart

    If you want your own function check this example:

    const myString = 'Welcome to my house';
    String.prototype.padLeft = function(times = 0, str = ' ') {
        return (Array(times).join(str) + this);
    }
    console.log(myString.padLeft(12, ':'));
    //:::::::::::Welcome to my house
    
    0 讨论(0)
  • 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 );
    });
    
    0 讨论(0)
  • 2020-11-22 08:58

    Array manipulations are really slow compared to simple string concat. Of course, benchmark for your use case.

    function(string, length, pad_char, append) {
        string = string.toString();
        length = parseInt(length) || 1;
        pad_char = pad_char || ' ';
    
        while (string.length < length) {
            string = append ? string+pad_char : pad_char+string;
        }
        return string;
    };
    
    0 讨论(0)
  • 2020-11-22 08:58

    I think its better to avoid recursion because its costly.

    function padLeft(str,size,padwith) {
    	if(size <= str.length) {
            // not padding is required.
    		return str;
    	} else {
            // 1- take array of size equal to number of padding char + 1. suppose if string is 55 and we want 00055 it means we have 3 padding char so array size should be 3 + 1 (+1 will explain below)
            // 2- now join this array with provided padding char (padwith) or default one ('0'). so it will produce '000'
            // 3- now append '000' with orginal string (str = 55), will produce 00055
    
            // why +1 in size of array? 
            // it is a trick, that we are joining an array of empty element with '0' (in our case)
            // if we want to join items with '0' then we should have at least 2 items in the array to get joined (array with single item doesn't need to get joined).
            // <item>0<item>0<item>0<item> to get 3 zero we need 4 (3+1) items in array   
    		return Array(size-str.length+1).join(padwith||'0')+str
    	}
    }
    
    alert(padLeft("59",5) + "\n" +
         padLeft("659",5) + "\n" +
         padLeft("5919",5) + "\n" +
         padLeft("59879",5) + "\n" +
         padLeft("5437899",5));

    0 讨论(0)
  • 2020-11-22 09:00

    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.

    0 讨论(0)
  • 2020-11-22 09:02

    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)); 
    }
    
    0 讨论(0)
提交回复
热议问题