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


当前回答

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

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

//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
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 pad(width, string, padding) { 
  return (width <= string.length) ? string : pad(width, padding + string, padding)
}

一个例子……

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

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