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

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

提交回复
热议问题