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


当前回答

这里有一个你可以使用的内置方法-

str1.padStart(2, '0')

其他回答

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

如果你不介意包含一个实用程序库,lodash库有_。垫,_。padLeft和_。padRight功能。

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

这是我使用的一个简单函数。

var pad=function(num,field){
    var n = '' + num;
    var w = n.length;
    var l = field.length;
    var pad = w < l ? l-w : 0;
    return field.substr(0,pad) + n;
};

例如:

pad    (20,'     ');    //   20
pad   (321,'     ');    //  321
pad (12345,'     ');    //12345
pad (   15,'00000');    //00015
pad (  999,'*****');    //**999
pad ('cat','_____');    //__cat  

ES7现在只是草案和建议,但如果你想跟踪与规范的兼容性,你的pad功能需要:

多字符pad支持。 不要截断输入字符串 Pad默认为空格

从我的填充库,但应用你自己的尽职调查的原型扩展。

// Tests
'hello'.lpad(4) === 'hello'
'hello'.rpad(4) === 'hello'
'hello'.lpad(10) === '     hello'
'hello'.rpad(10) === 'hello     '
'hello'.lpad(10, '1234') === '41234hello'
'hello'.rpad(10, '1234') === 'hello12341'

String.prototype.lpad || (String.prototype.lpad = function(length, pad)
{
    if(length < this.length)
        return this;

    pad = pad || ' ';
    let str = this;

    while(str.length < length)
    {
        str = pad + str;
    }

    return str.substr( -length );
});

String.prototype.rpad || (String.prototype.rpad = function(length, pad)
{
    if(length < this.length)
        return this;

    pad = pad || ' ';
    let str = this;

    while(str.length < length)
    {
        str += pad;
    }

    return str.substr(0, length);
});