Is there a JavaScript function that can pad a stri

2018-12-31 13:14发布

I am in need of a JavaScript function which can take a value and pad it to a given length (I need spaces, but anything would do). I found this:

Code:

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

Example:

<script type="text/javascript">
//<![CDATA[

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

//]]>
</script>

But I have no idea what the heck it is doing and it doesn't seem to work for me.

30条回答
大哥的爱人
2楼-- · 2018-12-31 13:51

A friend asked about using a JavaScript function to pad left. It turned into a little bit of an endeavor between some of us in chat to code golf it. This was the result:

function l(p,t,v){
    v+="";return v.length>=t?v:l(p,t,p+v); 
}

It ensures that the value to be padded is a string, and then if it isn't the length of the total desired length it will pad it once and then recurse. Here is what it looks like with more logical naming and structure

function padLeft(pad, totalLength, value){
    value = value.toString();

    if( value.length >= totalLength ){
        return value;
    }else{
        return padLeft(pad, totalLength, pad + value);
    }
}

The example we were using was to ensure that numbers were padded with 0 to the left to make a max length of 6. Here is an example set:

function l(p,t,v){v+="";return v.length>=t?v:l(p,t,p+v);}

var vals = [6451,123,466750];

var pad = l(0,6,vals[0]);// pad with 0's, max length 6

var pads = vals.map(function(i){ return l(0,6,i) });

document.write(pads.join("<br />"));

查看更多
伤终究还是伤i
3楼-- · 2018-12-31 13:52

Using the ECMAScript 6 method String#repeat and Arrow functions, a pad function is as simple as:

var leftPad = (s, c, n) => c.repeat(n - s.length) + s;
leftPad("foo", "0", 5); //returns "00foo"

jsfiddle

edit: suggestion from the comments:

const leftPad = (s, c, n) => n - s.length > 0 ? c.repeat(n - s.length) + s : s;

this way, it wont throw an error when s.lengthis greater than n

edit2: suggestion from the comments:

const leftPad = (s, c, n) =>{ s = s.toString(); c = c.toString(); return s.length > n ? s : c.repeat(n - s.length) + s; }

this way, you can use the function for strings and non-strings alike.

查看更多
冷夜・残月
4楼-- · 2018-12-31 13:52

Here is a JavaScript function that adds specified number of paddings with custom symble. the function takes three parameters.

    padMe --> string or number to left pad
    pads  --> number of pads
    padSymble --> custom symble, 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());
    }
/* Here are some results:

> leftPad(1)
"1"
> leftPad(1, 4)
"0001"
> leftPad(1, 4, "0")
"0001"
> leftPad(1, 4, "@")
"@@@1"

*/
查看更多
千与千寻千般痛.
5楼-- · 2018-12-31 13:54

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

查看更多
公子世无双
6楼-- · 2018-12-31 13:55

Based on the best answers of this question I have made a prototype for String called padLeft (exactly like we have in 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);
}

Usage:

var str = "12345";
console.log(str.padLeft("0", 10)); //Result is: "0000012345"

JsFiddle

查看更多
忆尘夕之涩
7楼-- · 2018-12-31 13:56

If you just want a very simple hacky one-liner to pad, just make a string of the desired padding character of the desired max padding length and then substring it to the length of what you want to pad.

Example: padding the string store in e with spaces to 25 characters long.

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

Result: "hello "

If you want to do the same with a number as input just call .toString() on it before.

查看更多
登录 后发表回答