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


当前回答

一种更快的方法

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

其他回答

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

可读性更强。

基于这个问题的最佳答案,我为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"

小提琴

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

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

使用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; }

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