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:43

String.prototype.padStart() and String.prototype.padEnd() are currently TC39 candidate proposals: see github.com/tc39/proposal-string-pad-start-end (only available in Firefox as of April 2016; a polyfill is available).

查看更多
孤独寂梦人
3楼-- · 2018-12-31 13:44

Array manipulations are really slow compared to simple string concat. Of course, benchmark for your use case.

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;
};
查看更多
旧人旧事旧时光
4楼-- · 2018-12-31 13:44

Here's my take

I'm not so sure about it's performance, but I find it much more readable than other options I saw around here...

var replicate = function(len, char) {
  return Array(len+1).join(char || ' ');
};

var padr = function(text, len, char) {
  if (text.length >= len) return text;
  return text + replicate(len-text.length, char);
};
查看更多
孤独寂梦人
5楼-- · 2018-12-31 13:46

pad with default values

I noticed that i mostly need the padLeft for time conversion / number padding

so i wrote this function

function padL(a,b,c){//string/number,length=2,char=0
 return (new Array(b||2).join(c||0)+a).slice(-b)
}

This simple function supports Number or String as input

default pad is 2 chars

default char is 0

so i can simply write

padL(1);
// 01

if i add the second argument (pad width)

padL(1,3);
// 001

third parameter (pad char)

padL('zzz',10,'x');
// xxxxxxxzzz

EDIT @BananaAcid if you pass a undefined value or a 0 length string you get 0undefined..so:

as suggested

function padL(a,b,c){//string/number,length=2,char=0
 return (new Array((b||1)+1).join(c||0)+(a||'')).slice(-(b||2))
}

but this can also be achieved in a shorter way.

function padL(a,b,c){//string/number,length=2,char=0
 return (new Array(b||2).join(c||0)+(a||c||0)).slice(-b)
}

works also with:

padL(0)
padL(NaN)
padL('')
padL(undefined)
padL(false)

And if you want to be able to pad in both ways :

function pad(a,b,c,d){//string/number,length=2,char=0,0/false=Left-1/true=Right
return a=(a||c||0),c=new Array(b||2).join(c||0),d?(a+c).slice(0,b):(c+a).slice(-b)
}

which can be written in a shorter way without using slice.

function pad(a,b,c,d){
 return a=(a||c||0)+'',b=new Array((++b||3)-a.length).join(c||0),d?a+b:b+a
}
/*

Usage:

pad(
 input // (int or string) or undefined,NaN,false,empty string
       // default:0 or PadCharacter
 // optional
 ,PadLength // (int) default:2
 ,PadCharacter // (string or int) default:'0'
 ,PadDirection // (bolean) default:0 (padLeft) - (true or 1) is padRight 
)

*/

now if you try to pad 'averylongword' with 2 ... thats not my problem.


Said that i give you a tip.

Most of the time if you pad you do it for the same value N times.

Using any type of function inside a loop slows down the loop!!!

So if you just wanna pad left some numbers inside a long list don't use functions to do this simple thing.

use something like this:

var arrayOfNumbers=[1,2,3,4,5,6,7],
    paddedArray=[],
    len=arrayOfNumbers.length;
while(len--){
 paddedArray[len]=('0000'+arrayOfNumbers[len]).slice(-4);
}

if you don't know how the max padding size based on the numbers inside the array.

var arrayOfNumbers=[1,2,3,4,5,6,7,49095],
    paddedArray=[],
    len=arrayOfNumbers.length;

// search the highest number
var arrayMax=Function.prototype.apply.bind(Math.max,null),
// get that string length
padSize=(arrayMax(arrayOfNumbers)+'').length,
// create a Padding string
padStr=new Array(padSize).join(0);
// and after you have all this static values cached start the loop.
while(len--){
 paddedArray[len]=(padStr+arrayOfNumbers[len]).slice(-padSize);//substr(-padSize)
}
console.log(paddedArray);

/*
0: "00001"
1: "00002"
2: "00003"
3: "00004"
4: "00005"
5: "00006"
6: "00007"
7: "49095"
*/
查看更多
十年一品温如言
6楼-- · 2018-12-31 13:47

I found this solution here and this is for me much much simpler:

var n = 123

String("00000" + n).slice(-5); // returns 00123
("00000" + n).slice(-5); // returns 00123
("     " + n).slice(-5); // returns "  123" (with two spaces)

And here I made an extension to the string object:

String.prototype.paddingLeft = function (paddingValue) {
   return String(paddingValue + this).slice(-paddingValue.length);
};

An example to use it:

function getFormattedTime(date) {
  var hours = date.getHours();
  var minutes = date.getMinutes();

  hours = hours.toString().paddingLeft("00");
  minutes = minutes.toString().paddingLeft("00");

  return "{0}:{1}".format(hours, minutes);
};

String.prototype.format = function () {
    var args = arguments;
    return this.replace(/{(\d+)}/g, function (match, number) {
        return typeof args[number] != 'undefined' ? args[number] : match;
    });
};

This will return a time in the format "15:30"

查看更多
一个人的天荒地老
7楼-- · 2018-12-31 13:47

It's 2014, and I suggest a Javascript string-padding function. Ha!

Bare-bones: right-pad with spaces

function pad ( str, length ) {
    var padding = ( new Array( Math.max( length - str.length + 1, 0 ) ) ).join( " " );
    return str + padding;
}

Fancy: pad with options

/**
 * @param {*}       str                         input string, or any other type (will be converted to string)
 * @param {number}  length                      desired length to pad the string to
 * @param {Object}  [opts]
 * @param {string}  [opts.padWith=" "]          char to use for padding
 * @param {boolean} [opts.padLeft=false]        whether to pad on the left
 * @param {boolean} [opts.collapseEmpty=false]  whether to return an empty string if the input was empty
 * @returns {string}
 */
function pad ( str, length, opts ) {
    var padding = ( new Array( Math.max( length - ( str + "" ).length + 1, 0 ) ) ).join( opts && opts.padWith || " " ),
        collapse = opts && opts.collapseEmpty && !( str + "" ).length;
    return collapse ? "" : opts && opts.padLeft ? padding + str : str + padding;
}

Usage (fancy):

pad( "123", 5 );
// returns "123  "

pad( 123, 5 );
// returns "123  " - non-string input

pad( "123", 5, { padWith: "0", padLeft: true } );
// returns "00123"

pad( "", 5 );
// returns "     "

pad( "", 5, { collapseEmpty: true } );
// returns ""

pad( "1234567", 5 );
// returns "1234567"
查看更多
登录 后发表回答