我需要一个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) );


当前回答

使用默认值的填充

我注意到我主要需要padLeft进行时间转换/数字填充。

所以我写了这个函数:

function padL(a, b, c) { // string/number, length=2, char=0
  return (new Array(b || 2).join(c || 0) + a).slice(-b)
}

这个简单的函数支持数字或字符串作为输入。

默认的pad是两个字符。

默认字符为0。

所以我可以简单地写:

padL(1);
// 01

如果我添加第二个参数(pad width):

padL(1, 3);
// 001

第三个参数(填充字符)

padL('zzz', 10, 'x');
// xxxxxxxzzz

@BananaAcid:如果你传递一个未定义的值或长度为0的字符串,你会得到0undefined,所以:

作为建议

function padL(a, b, c) { // string/number, length=2, char=0
  return (new Array((b || 1) + 1).join(c || 0) + (a || '')).slice(-(b || 2))
}

但这也可以用更短的方式实现。

function padL(a, b, c) { // string/number, length=2, char=0
  return (new Array(b || 2).join(c || 0) + (a || c || 0)).slice(-b)
}

它还适用于:

padL(0)
padL(NaN)
padL('')
padL(undefined)
padL(false)

如果你想用两种方式填充:

function pad(a, b, c, d) { // string/number, length=2, char=0, 0/false=Left-1/true=Right
  return a = (a || c || 0), c = new Array(b || 2).join(c || 0), d ? (a + c).slice(0, b) : (c + a).slice(-b)
}

不用slice就可以写得更简洁。

function pad(a, b, c, d) {
  return a = (a || c || 0) + '', b = new Array((++b || 3) - a.length).join(c || 0), d ? a+b : b+a
}
/*

Usage:

pad(
 input // (int or string) or undefined, NaN, false, empty string
       // default:0 or PadCharacter
 // Optional
 ,PadLength // (int) default:2
 ,PadCharacter // (string or int) default:'0'
 ,PadDirection // (bolean) default:0 (padLeft) - (true or 1) is padRight
)

*/

现在如果你试着用2填充'averylongword'…那不是我的问题。


我说过我会给你小费。

大多数情况下,如果你填充,你会做N次相同的值。

在循环中使用任何类型的函数都会降低循环的速度!!

所以如果你只是想在一个长列表中填充一些数字,不要使用函数来做这个简单的事情。

可以这样说:

var arrayOfNumbers = [1, 2, 3, 4, 5, 6, 7],
    paddedArray = [],
    len = arrayOfNumbers.length;
while(len--) {
  paddedArray[len] = ('0000' + arrayOfNumbers[len]).slice(-4);
}

如果你不知道如何根据数组内的数字来确定最大填充大小。

var arrayOfNumbers = [1, 2, 3, 4, 5, 6, 7, 49095],
    paddedArray = [],
    len = arrayOfNumbers.length;

// Search the highest number
var arrayMax = Function.prototype.apply.bind(Math.max, null),
// Get that string length
padSize = (arrayMax(arrayOfNumbers) + '').length,
// Create a Padding string
padStr = new Array(padSize).join(0);
// And after you have all this static values cached start the loop.
while(len--) {
  paddedArray[len] = (padStr + arrayOfNumbers[len]).slice(-padSize); // substr(-padSize)
}
console.log(paddedArray);

/*
0: "00001"
1: "00002"
2: "00003"
3: "00004"
4: "00005"
5: "00006"
6: "00007"
7: "49095"
*/

其他回答

ECMAScript 2017在String原型中增加了一个padStart方法。这个方法将用空格填充字符串到给定的长度。此方法还接受一个可选字符串,该字符串将用于代替空格作为填充。

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

还添加了以相同方式工作的padEnd方法。

关于浏览器兼容性(和一个有用的填充),请参见此链接。

像PHP:

const STR_PAD_RIGHT = 1;
const STR_PAD_LEFT = 0;
const STR_PAD_BOTH = 2;

/**
 * @see http://php.net/str_pad
 * @param mixed input 
 * @param integer length 
 * @param string string 
 * @param integer type 
 * @return string
 */
function str_pad(input, length, string, type) {
    if (type === undefined || (type !== STR_PAD_LEFT && type !== STR_PAD_BOTH)) {
        type = STR_PAD_RIGHT
    }

    if (input.toString().length >= length) {
         return input;
    } else {
        if (type === STR_PAD_BOTH) {
            input = (string + input + string);
        } else if (type == STR_PAD_LEFT) {
            input = (string + input);
        } else {
            input = (input + string);
        }

        return str_pad(input.toString(), length, string, type);
    }
}

ECMAScript 2017 (ES8)增加了字符串。padStart(连同String.padEnd)来实现这个目的:

"Jonas".padStart(10); // Default pad string is a space
"42".padStart(6, "0"); // Pad with "0"
"*".padStart(8, "-/|\\"); // produces '-/|\\-/|*'

如果没有出现在JavaScript主机中,则字符串。padStart可以作为polyfill添加。

ES8的

我在这里找到了这个解,对我来说简单得多:

var n = 123

String("00000" + n).slice(-5); // returns 00123
("00000" + n).slice(-5); // returns 00123
("     " + n).slice(-5); // returns "  123" (with two spaces)

这里我对string对象做了一个扩展:

String.prototype.paddingLeft = function (paddingValue) {
   return String(paddingValue + this).slice(-paddingValue.length);
};

使用它的例子:

function getFormattedTime(date) {
  var hours = date.getHours();
  var minutes = date.getMinutes();

  hours = hours.toString().paddingLeft("00");
  minutes = minutes.toString().paddingLeft("00");

  return "{0}:{1}".format(hours, minutes);
};

String.prototype.format = function () {
    var args = arguments;
    return this.replace(/{(\d+)}/g, function (match, number) {
        return typeof args[number] != 'undefined' ? args[number] : match;
    });
};

这将返回格式为“15:30”的时间。

捷径:

(x=>(new Array(int-x.length+1)).join(char)+x)(String)

例子:

(x=>(new Array(6-x.length+1)).join("0")+x)("1234")

返回:“001234”

Never insert data somewhere (especially not at beginning, like str = pad + str;), since the data will be reallocated everytime. Append always at end! Don't pad your string in the loop. Leave it alone and build your pad string first. In the end concatenate it with your main string. Don't assign padding string each time (like str += pad;). It is much faster to append the padding string to itself and extract first x-chars (the parser can do this efficiently if you extract from first char). This is exponential growth, which means that it wastes some memory temporarily (you should not do this with extremely huge texts).

if (!String.prototype.lpad) { String.prototype.lpad =函数(pad, len) { 而(pad。长度< len) { Pad += Pad; } 返回垫。Substr (0, lens -this.length) + this; } } if (!String.prototype.rpad) { String.prototype.rpad = function(pad, len) { 而(pad。长度< len) { Pad += Pad; } 返回这个+ pad。substr (0, len-this.length); } }