5

Is there a built in function to pad characters n number of times?

Ex:

var myString = 'something';
var myCharToPad = '-';
var numTimesToPad = 5;

I am expecting myString = 'something-----';

Dusty
  • 2,159
  • 3
  • 23
  • 26
  • possible duplicate of [Repeat String - Javascript](http://stackoverflow.com/questions/202605/repeat-string-javascript) – genesis Jul 14 '11 at 23:08
  • Paddnig is usually at the front of the string, do you need the option of which end to pad? – RobG Jul 14 '11 at 23:12

3 Answers3

14

No, but it's not hard:

myString += new Array(numTimesToPad+1).join(myCharToPad);
  • Why the `numTimesToPad+1` while declaring the `Array`? – Dusty Jul 15 '11 at 13:56
  • @Tim Down - not true. It makes assigning large arrays much, much quicker. @Dusty - because `new Array(1).join('-')` gives `""` –  Jul 15 '11 at 15:29
  • @Tim Down - Yes. :/ You just helped me find a ___very___ interesting bug (at least to me): http://jsperf.com/newarrayassign/2 (view in chrome) –  Jul 15 '11 at 17:59
  • @cwolves: It's an odd set of results in all versions of Chrome listed there. There must some internal Chrome heuristics going on. – Tim Down Jul 16 '11 at 11:26
  • @Tim Down - Chrome allocates memory for the entire array if there are < 100,000 elements. Once it hits 100,000 it stops (makes sense, in case someone does `new Array(1,000,000,000)`. So it's faster to pre-define the array up-to 100,000 elements :) (in chrome). Other browsers vary, but there are benchmarks that it is almost always a good thing. –  Jul 16 '11 at 17:13
  • @cwolves: Yes, that was my assumption too. What I found odd was that my random choice of large number for the test happened to be the cut-off point for Chrome's heuristics. – Tim Down Jul 17 '11 at 10:32
2

Nope, but it's trivial to write one:

function pad(num, string, char) {
    for (var i = 0; i < num; i++) {
        string += char;
    }
    return string;
}

var myString = pad(5, 'something', '-')
bcoughlan
  • 25,987
  • 18
  • 90
  • 141
-1

This is a repeated entry; you should always check first and if nobody has an answer, which is almost impossible [sorry but chances are that you are not that special] then post... that even saves you time by solving your issue faster. You can find my "almost" ultimate answer to the JS padding issue at here! also on this site.

Community
  • 1
  • 1