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


当前回答

试试这个:

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

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

其他回答

这是一个递归的方法。

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

一个例子……

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

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

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

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

结果:“hello”

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

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

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

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

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