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


当前回答

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

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

例子:

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

其他回答

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

一种更快的方法

If you are doing this repeatedly, for example to pad values in an array, and performance is a factor, the following approach can give you nearly a 100x advantage in speed (jsPerf) over other solution that are currently discussed on the inter webs. The basic idea is that you are providing the pad function with a fully padded empty string to use as a buffer. The pad function just appends to string to be added to this pre-padded string (one string concat) and then slices or trims the result to the desired length.

function pad(pad, str, padLeft) {
  if (typeof str === 'undefined') 
    return pad;
  if (padLeft) {
    return (pad + str).slice(-pad.length);
  } else {
    return (str + pad).substring(0, pad.length);
  }
}

例如,要将一个数字零填充为10位,

pad('0000000000',123,true);

要用空格填充字符串,使整个字符串为255个字符,

var padding = Array(256).join(' '), // make a string of 255 spaces
pad(padding,123,true);

性能测试

请在这里查看jsPerf测试。

这比ES6字符串快。重复2倍,正如这里修改后的JsPerf所示

请注意,jsPerf不再联机

请注意,我们最初用来对各种方法进行基准测试的jsPerf站点已不再在线。不幸的是,这意味着我们无法得到那些测试结果。虽然悲伤,但事实如此。

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

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

包括所有选项

function padding(stringToBePadded, paddingCharacter, totalLength, padLeftElseRight){
    //will pad any string provided in first argument, with padding character provide in 2nd argument and truncate to lenght provided in third argument, padding left if 4th argument true or undefined, right if false. 
    // i.e. padding("lode","x","10")  -->  "xxxxxxlode"
    // i.e. padding("lode","x","10",true)  -->  "xxxxxxlode"
    // i.e. padding("lode","x","10",false)  -->  "lodexxxxxx"
    // i.e. padding("12","0","5")  -->  "00012"
    {
        padLeftElseRight = typeof padLeftElseRight !== 'undefined' ? padLeftElseRight : true;
    }
    if (stringToBePadded.length > totalLength){
        // console.log("string too long to be padded");
        return stringToBePadded;
    }
    var paddingString = paddingCharacter.repeat(totalLength);//make long string of padding characters
    if ( padLeftElseRight){
        return String(paddingString+stringToBePadded).slice(-totalLength);
    }else{ 
        return String(stringToBePadded+paddingString).slice(0,totalLength); 
    }
}

@Daniel LaFavers回答的一个变体。

var mask = function (background, foreground) {
  bg = (new String(background));
  fg = (new String(foreground));
  bgl = bg.length;
  fgl = fg.length;
  bgs = bg.substring(0, Math.max(0, bgl - fgl));
  fgs = fg.substring(Math.max(0, fgl - bgl));
  return bgs + fgs;
};

例如:

mask('00000', 11  );   // '00011'
mask('00011','00' );   // '00000'
mask( 2     , 3   );   // '3'
mask('0'    ,'111');   // '1'
mask('fork' ,'***');   // 'f***'
mask('_____','dog');   // '__dog'