我需要一个JavaScript函数,它可以取一个值,并将其填充到给定的长度(我需要空格,但任何事情都会做)。我发现了这个,但我不知道它在做什么,它似乎对我不起作用。

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


当前回答

现在是2014年,我建议使用JavaScript字符串填充函数。哈!

基本的:带空格的右垫

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

花式:选项垫

/**
 * @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=" "]          Character 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;
}

使用(的):

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"

其他回答

有点晚了,但我还是想分享一下。我发现向Object添加一个原型扩展很有用。这样我就可以填充数字和字符串,向左或向右。我有一个模块与类似的实用程序,我包括在我的脚本。

// 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;
    }
};
/**************************************************************************************************
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;
}

然后你可以这样做:

alert( "3".pad("0", 3) ); //shows "003"
alert( "hi".pad(" ", 3) ); //shows " hi"
alert( "hi".pad(" ", 3, true) ); //shows "hi "

如果你想要一些紧凑的东西,只需一行:

String.prototype.pad = function(len, chr){ 返回((((新数组(len)) .fill(杆)). join (" ") +) .substring (this.length)); }

String.prototype.padStart()和String.prototype.padEnd()目前是TC39候选提案:参见github.com/tc39/proposal-string-pad-start-end(仅在2016年4月在Firefox中可用;有填充材料可用)。

这是一个递归的方法。

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

一个例子……

pad(5, 'hi', '0')
=> "000hi"