Is there a JavaScript function that can pad a string to get to a determined length?

前端 未结 30 1335
悲哀的现实
悲哀的现实 2020-11-22 08:28

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:

30条回答
  •  忘了有多久
    2020-11-22 09:08

    Here's a simple function that I use.

    var pad=function(num,field){
        var n = '' + num;
        var w = n.length;
        var l = field.length;
        var pad = w < l ? l-w : 0;
        return field.substr(0,pad) + n;
    };
    

    For example:

    pad    (20,'     ');    //   20
    pad   (321,'     ');    //  321
    pad (12345,'     ');    //12345
    pad (   15,'00000');    //00015
    pad (  999,'*****');    //**999
    pad ('cat','_____');    //__cat  
    

提交回复
热议问题