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


当前回答

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

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

其他回答

我喜欢这样做,以防你需要填充多个字符或标签(例如&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;
}

一个朋友问我如何使用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 / > "));

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

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

使用重复,会更简单。

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

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