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


当前回答

下面是一个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"

其他回答

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

包括所有选项

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

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

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

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

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

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

结果:“hello”

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

这是我的函数版本:

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