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


http://www.webtoolkit.info/javascript_pad.html

/**
*
*  JavaScript string pad
*  http://www.webtoolkit.info/
*
**/

var STR_PAD_LEFT = 1;
var STR_PAD_RIGHT = 2;
var STR_PAD_BOTH = 3;

function pad(str, len, pad, dir) {

    if (typeof(len) == "undefined") { var len = 0; }
    if (typeof(pad) == "undefined") { var pad = ' '; }
    if (typeof(dir) == "undefined") { var dir = STR_PAD_RIGHT; }

    if (len + 1 >= str.length) {

        switch (dir){

            case STR_PAD_LEFT:
                str = Array(len + 1 - str.length).join(pad) + str;
            break;

            case STR_PAD_BOTH:
                var padlen = len - str.length;
                var right = Math.ceil( padlen / 2 );
                var left = padlen - right;
                str = Array(left+1).join(pad) + str + Array(right+1).join(pad);
            break;

            default:
                str = str + Array(len + 1 - str.length).join(pad);
            break;

        } // switch

    }

    return str;
}

可读性更强。


这两种解决方案的关键技巧是创建具有给定大小(比所需长度大一个)的数组实例,然后立即调用join()方法来生成字符串。join()方法被传递填充字符串(可能是空格)。由于数组是空的,在将数组连接到一个结果字符串的过程中,空单元格将被呈现为空字符串,只有填充将保留。这是一个很好的技巧。


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”的时间。


这是一个递归的方法。

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

一个例子……

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

与简单的字符串连接相比,数组操作真的很慢。当然,是用例的基准测试。

function(string, length, pad_char, append) {
    string = string.toString();
    length = parseInt(length) || 1;
    pad_char = pad_char || ' ';

    while (string.length < length) {
        string = append ? string+pad_char : pad_char+string;
    }
    return string;
};

以下是我的看法:

我不太确定它的性能,但我发现它比我在这里看到的其他选项更具可读性……

var replicate = function(len, char) {
  return Array(len + 1).join(char || ' ');
};

var padr = function(text, len, char) {
  if (text.length >= len)
    return text;
  return text + replicate(len-text.length, char);
};

/**************************************************************************************************
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 "

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

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  

@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'

下面是一个JavaScript函数,它使用自定义符号添加指定数量的填充。该函数接受三个参数。

padMe --> string or number to left pad
pads  --> number of pads
padSymble --> custom symbol, default is "0"
function leftPad(padMe, pads, padSymble) {
    if(typeof padMe === "undefined") {
        padMe = "";
    }
    if (typeof pads === "undefined") {
        pads = 0;
    }
    if (typeof padSymble === "undefined") {
        padSymble = "0";
    }

    var symble = "";
    var result = [];
    for(var i=0; i < pads; i++) {
       symble += padSymble;
    }
    var length = symble.length - padMe.toString().length;
    result = symble.substring(0, length);
    return result.concat(padMe.toString());
}

以下是一些结果:

> leftPad(1)
"1"

> leftPad(1, 4)
"0001"

> leftPad(1, 4, "0")
"0001"

> leftPad(1, 4, "@")
"@@@1"

使用默认值的填充

我注意到我主要需要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"
*/

函数 var _padLeft = function(paddingString, width, replacementChar) { paddingString返回。长度>=宽度?paddingString: _padLeft(replacementChar + paddingString, width, replacementChar || ' '); }; 字符串的原型 String.prototype.padLeft = function(width, replacementChar) { 返回。长度>=宽度?this. tostring ():(replacementChar + this)。padLeft(width, replacementChar || ' '); }; 片 ('00000' + paddingString).slice(-5)


如果你只是想要一个非常简单的单行程序来填充,只需创建一个所需填充字符的字符串,以及所需的最大填充长度,然后将其子字符串转换为你想要填充的长度。

示例:用空格填充e中的字符串存储到25个字符长。

var e = "hello"; e = e + "                         ".substring(e.length)

结果:“hello”

如果你想用一个数字作为输入做同样的事情,只需在它之前调用. tostring()。


一种更快的方法

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站点已不再在线。不幸的是,这意味着我们无法得到那些测试结果。虽然悲伤,但事实如此。


基于这个问题的最佳答案,我为String做了一个名为padLeft的原型(就像我们在c#中所做的一样):

String.prototype.padLeft = function (paddingChar, totalWidth) {
    if (this.toString().length >= totalWidth)
        return this.toString();

    var array = new Array(totalWidth); 

    for (i = 0; i < array.length; i++)
        array[i] = paddingChar;

    return (array.join("") + this.toString()).slice(-array.length);
}

用法:

var str = "12345";
console.log(str.padLeft("0", 10)); //Result is: "0000012345"

小提琴


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

使用ECMAScript 6方法String#repeat,一个pad函数就像这样简单:

String.prototype.padLeft = function(char, length) {
    return char.repeat(Math.max(0, length - this.length)) + this;
}

字符串#repeat目前仅在Firefox和Chrome中支持。对于其他实现,可以考虑以下简单的polyfill:

String.prototype.repeat = String.prototype.repeat || function(n){
    return n<=1 ? this : (this + this.repeat(n-1));
}

试试这个:

function leftPad(number) {
    return (number < 9) ? '0' + number : number;
}

// Call it like this
var month = 3;
month = leftPad(month); // Output: month=04

还有一种结合了几个解决方案的方法:

/**
 * pad string on left
 * @param {number} number of digits to pad, default is 2
 * @param {string} string to use for padding, default is '0' *
 * @returns {string} padded string
 */
String.prototype.paddingLeft = function (b, c) {
    if (this.length > (b||2))
        return this + '';
  return (this || c || 0) + '', b = new Array((++b || 3) - this.length).join(c || 0), b + this
};

/**
 * pad string on right
 * @param {number} number of digits to pad, default is 2
 * @param {string} string to use for padding, default is '0' *
 * @returns {string} padded string
 */
String.prototype.paddingRight = function (b, c) {
  if (this.length > (b||2))
        return this + '';
  return (this||c||0) + '', b = new Array((++b || 3) - this.length).join(c || 0), this + b
};

继承塞缪尔的想法,在上面这里。记住一个旧的SQL脚本,我尝试了这个:

a=1234;
'0000'.slice(a.toString().length)+a;

它适用于我能想到的所有情况:

a=     1 result  0001
a=    12 result  0012
a=   123 result  0123
a=  1234 result  1234
a= 12345 result 12345
a=  '12' result  0012

String.prototype.padLeft = function(pad) {
        var s = Array.apply(null, Array(pad)).map(function() { return "0"; }).join('') + this;
        return s.slice(-1 * Math.max(this.length, pad));
    };

用法:

“123”.padLeft(2) 返回:“123” “12”.padLeft(2) 返回:“12” “1”.padLeft(2) 返回:“01”


包括所有选项

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

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

这里有一个简单的答案,基本上只有一行代码。

var value = 35 // the numerical value
var x = 5 // the minimum length of the string

var padded = ("00000" + value).substr(-x);

确保你填充的字符数量,这里的0,至少和你预期的最小长度一样多。因此,实际上,把它放在一行中,在这种情况下,得到“00035”的结果是:

var padded = ("00000" + 35).substr(-5);

我喜欢这样做,以防你需要填充多个字符或标签(例如&nbsp;)来显示:

$.padStringLeft = function(s, pad, len) {
    if(typeof s !== 'undefined') {
        var c=s.length; while(len > c) {s=pad+s;c++;}
    }
    return s;
}    

$.padStringRight = function(s, pad, len) {
    if(typeof s !== 'undefined') {
        var c=s.length; while(len > c) {s += pad;c++;}
    }
    return s;
}

我将上述解决方案的组合添加到我自己的,总是不断发展的版本:)

//in preperation for ES6
String.prototype.lpad || (String.prototype.lpad = function( length, charOptional )
{
    if (length <= this.length) return this;
    return ( new Array((length||0)+1).join(String(charOptional)||' ') + (this||'') ).slice( -(length||0) );
});


'abc'.lpad(5,'.') == '..abc'
String(5679).lpad(10,0) == '0000005679'
String().lpad(4,'-') == '----' // repeat string

如果你不介意包含一个实用程序库,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));


一个朋友问我如何使用JavaScript函数向左填充。它变成了我们中的一些人在聊天中努力编码高尔夫球。结果是:

function l(p,t,v){
    v+="";return v.length>=t?v:l(p,t,p+v); 
}

它确保要填充的值是一个字符串,然后如果它不是所需的总长度,它将填充一次,然后递归。下面是它看起来更有逻辑的命名和结构

function padLeft(pad, totalLength, value){
    value = value.toString();

    if( value.length >= totalLength ){
        return value;
    }else{
        return padLeft(pad, totalLength, pad + value);
    }
}

我们所使用的示例是确保数字在左边用0填充,使最大长度为6。下面是一个例子:

函数l (p t v) {v + = " ";返回v.length > = t ? v: l (p t, p + v);} Var vals = [6451,123,466750]; Var pad = l(0,6,vals[0]);// pad为0,最大长度为6 Var pads = vals.map(函数(i){返回l(0,6,i)}); document . write(垫。加入(“< br / > "));


有点晚了,但我还是想分享一下。我发现向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;
    }
};

使用ECMAScript 6方法String#repeat和Arrow函数,一个pad函数就像这样简单:

var leftPad = (s, c, n) => c.repeat(n - s.length) + s;
leftPad("foo", "0", 5); //returns "00foo"

斯菲德尔

编辑: 评论中的建议:

const leftPad = (s, c, n) => n - s.length > 0 ? c.repeat(n - s.length) + s : s;

这样,当s.lengthis大于n时,它就不会抛出错误

edit2: 评论中的建议:

const leftPad = (s, c, n) =>{ s = s.toString(); c = c.toString(); return s.length > n ? s : c.repeat(n - s.length) + s; }

通过这种方式,可以将该函数用于字符串和非字符串。


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


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

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


使用重复,会更简单。

    var padLeft=function(str, pad, fw){
        return fw>str.length ? pad.repeat(fw-str.length)+str : str;
    }

你可以这样使用它: padeLeft('origin-str', '0', 20)


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

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


这是我的函数版本:

function str_pad(str, size, char, right) {
    var s = str + "";
    while (s.length < size) {
        if (right) {
            s = s + char;
        } else {
            s = char + s;
        }
    }
    return s;
}

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

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

例子:

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

在ES8中,有两个填充选项。

您可以在文档中查看它们。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padEnd

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart


捷径:

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

例子:

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

返回:“001234”


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

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


填充字符串已在新的javascript版本中实现。

str.padStart(目标,pad弦)

https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Objetos_globales/String/padStart

如果你想要自己的函数,检查这个例子:

const myString = 'Welcome to my house';
String.prototype.padLeft = function(times = 0, str = ' ') {
    return (Array(times).join(str) + this);
}
console.log(myString.padLeft(12, ':'));
//:::::::::::Welcome to my house

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

str1.padStart(2, '0')