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


当前回答

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

其他回答

现在是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"

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

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方法。

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

对于这样的东西,我可能会在需要它的地方创建一个单行函数:

var padleft = (s,c,len) => { while(s.length < len) s = c + s; return s; }

例子:

> console.log( padleft( '110', '0', 8) );
> 00000110

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