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

前端 未结 30 1276
悲哀的现实
悲哀的现实 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 09:11

    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"

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

    If you don't mind including a utility library, lodash library has _.pad, _.padLeft and _.padRight functions.

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

    It's 2014, and I suggest a Javascript string-padding function. Ha!

    Bare-bones: right-pad with spaces

    function pad ( str, length ) {
        var padding = ( new Array( Math.max( length - str.length + 1, 0 ) ) ).join( " " );
        return str + padding;
    }
    

    Fancy: pad with options

    /**
     * @param {*}       str                         input string, or any other type (will be converted to string)
     * @param {number}  length                      desired length to pad the string to
     * @param {Object}  [opts]
     * @param {string}  [opts.padWith=" "]          char to use for padding
     * @param {boolean} [opts.padLeft=false]        whether to pad on the left
     * @param {boolean} [opts.collapseEmpty=false]  whether to return an empty string if the input was empty
     * @returns {string}
     */
    function pad ( str, length, opts ) {
        var padding = ( new Array( Math.max( length - ( str + "" ).length + 1, 0 ) ) ).join( opts && opts.padWith || " " ),
            collapse = opts && opts.collapseEmpty && !( str + "" ).length;
        return collapse ? "" : opts && opts.padLeft ? padding + str : str + padding;
    }
    

    Usage (fancy):

    pad( "123", 5 );
    // returns "123  "
    
    pad( 123, 5 );
    // returns "123  " - non-string input
    
    pad( "123", 5, { padWith: "0", padLeft: true } );
    // returns "00123"
    
    pad( "", 5 );
    // returns "     "
    
    pad( "", 5, { collapseEmpty: true } );
    // returns ""
    
    pad( "1234567", 5 );
    // returns "1234567"
    
    0 讨论(0)
  • 2020-11-22 09:14

    A little late, but thought I might share anyway. I found it useful to add a prototype extension to Object. That way I can pad numbers and strings, left or right. I have a module with similar utilities I include in my scripts.

    // include the module in your script, there is no need to export
    var jsAddOns = require('<path to module>/jsAddOns');
    

    ~~~~~~~~~~~~ jsAddOns.js ~~~~~~~~~~~~

    /* 
     * method prototype for any Object to pad it's toString()
     * representation with additional characters to the specified length
     *
     * @param padToLength required int
     *     entire length of padded string (original + padding)
     * @param padChar optional char
     *     character to use for padding, default is white space
     * @param padLeft optional boolean
     *     if true padding added to left
     *     if omitted or false, padding added to right
     *
     * @return padded string or
     *     original string if length is >= padToLength
     */
    Object.prototype.pad = function(padToLength, padChar, padLeft) {    
    
        // get the string value
        s = this.toString()
    
        // default padToLength to 0
        // if omitted, original string is returned
        padToLength = padToLength || 0;
    
        // default padChar to empty space
        padChar = padChar || ' ';
    
    
        // ignore padding if string too long
        if (s.length >= padToLength) {
            return s;
        }
    
        // create the pad of appropriate length
        var pad = Array(padToLength - s.length).join(padChar);
    
        // add pad to right or left side
        if (padLeft) {
            return pad  + s;        
        } else {
            return s + pad;
        }
    };
    
    0 讨论(0)
  • 2020-11-22 09:15

    A faster method

    If you are doing this repeatedly, for example to pad values in an array, and performance is a factor, the following approach can give you nearly a 100x advantage in speed (jsPerf) over other solution that are currently discussed on the inter webs. The basic idea is that you are providing the pad function with a fully padded empty string to use as a buffer. The pad function just appends to string to be added to this pre-padded string (one string concat) and then slices or trims the result to the desired length.

    function pad(pad, str, padLeft) {
      if (typeof str === 'undefined') 
        return pad;
      if (padLeft) {
        return (pad + str).slice(-pad.length);
      } else {
        return (str + pad).substring(0, pad.length);
      }
    }
    

    For example, to zero pad a number to a length of 10 digits,

    pad('0000000000',123,true);
    

    To pad a string with whitespace, so the entire string is 255 characters,

    var padding = Array(256).join(' '), // make a string of 255 spaces
    pad(padding,123,true);
    

    Performance Test

    See the jsPerf test here.

    And this is faster than ES6 string.repeat by 2x as well, as shown by the revised JsPerf here

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

    ECMAScript 2017 adds a padStart method to the String prototype. This method will pad a string with spaces to a given length. This method also takes an optional string that will be used instead of spaces for padding.

    'abc'.padStart(10);         // "       abc"
    'abc'.padStart(10, "foo");  // "foofoofabc"
    'abc'.padStart(6,"123465"); // "123abc"
    'abc'.padStart(8, "0");     // "00000abc"
    'abc'.padStart(1);          // "abc"
    

    A padEnd method was also added that works in the same manner.

    For browser compatibility (and a useful polyfill) see this link.

    0 讨论(0)
提交回复
热议问题