1

The best way to explain this is with examples.

Let's say I have the integer 5. I plug it into a function, and it would return the space character (" ") 5 times in a single variable, like "     ".

I have the integer 3. I plug it into a function, and the output would be "   " (3 spaces).

Hopefully you get the point. What is the best way to accomplish this. I feel like there is a really simple way to do this in JavaScript, with or without loops, that I am missing. Thanks.

Gus
  • 1,905
  • 6
  • 23
  • 37
  • 1
    This appears to be answered in http://stackoverflow.com/questions/1877475/repeat-character-n-times. – Jeremiah Willcock Feb 10 '11 at 03:35
  • @drachenstern It isn't a big leap to go from arbitrary strings to spaces. – Ates Goral Feb 10 '11 at 03:44
  • @drachenstern: I edited it (maybe after you saw it) to a new link that is only about single characters. – Jeremiah Willcock Feb 10 '11 at 03:44
  • @Jeremiah, you did. @AtesGoral ~ You miss my point. Let's not do a link on arbitrary strings when the question was for spaces. Answer the specific question, not the advanced alternatives. – jcolebrand Feb 10 '11 at 03:48
  • Thanks, I was looking around for ages, I just didn't think about searching for that specific wording. The best way to do it seems to be Array(int).join(" "). – Gus Feb 10 '11 at 03:53
  • 1
    @Gus That would be the fastest, yes. Most readable, maybe not so much. – jcolebrand Feb 10 '11 at 03:53

6 Answers6

4
function nSpaces(n) {
    var s = '';
    while (n > 0 && n--) { s += ' '; }
    return s;
}

And then ...

var str = nSpaces(5); 

For more information about the reverse while loop and looping in general, read here: http://james.padolsey.com/javascript/looping-in-javascript/

Šime Vidas
  • 182,163
  • 62
  • 281
  • 385
  • @drachenstern I wouldn't call it a trick. It's just one way to loop. – Šime Vidas Feb 10 '11 at 03:42
  • It's a pretty common paradigm - the risk is if `n` is less than 0 to begin with. – Hamish Feb 10 '11 at 03:46
  • @Hamish Ah yes, negative arguments create an infinite loop (which crashes my Chrome by the way LOL). I'll fix it. – Šime Vidas Feb 10 '11 at 03:52
  • @drachenstern The reverse loop really isn't that advanced. But I don't agree that beginners should not get a glimpse of the advanced "stuff". They of all people should see the tricks and hacks of JavaScript. Otherwise, how are they going to learn? – Šime Vidas Feb 10 '11 at 04:06
  • @drachenstern Yes, providing links to articles that give further explanations sounds like a good idea. I've updated my answer. – Šime Vidas Feb 10 '11 at 04:15
3
function repeatCh( ch, num ) {    
  return new Array( num + 1 ).join( ch );
}
Chris Hogan
  • 868
  • 6
  • 9
2
function spaces(size) {
    for(var output = ""; size > 0; size--) output += " ";
    return output;
}

A shorter version :)

function spaces(n) {
    for(var s="";n--;s+=" "){}return s;
}
Hamish
  • 22,860
  • 8
  • 53
  • 67
  • That's pretty tricky. I like it. But won't output be out of scope outside the loop? – jcolebrand Feb 10 '11 at 03:36
  • Nope, `var` will keep output in the local scope (`function spaces`). Apparently, using `let` instead of `var` would keep it within the block scope as well. – Hamish Feb 10 '11 at 03:41
  • Nice. I wasn't aware of that. I know in C you should expect it to fall out of scope. I'm gonna have to remember that one. Thanks. – jcolebrand Feb 10 '11 at 03:44
  • yay for the straightforward way not crashing the browser (altho an infinite loop may conceivably occur) – jcolebrand Feb 10 '11 at 04:05
  • yeah the second version has that problem.. could put `n--&&n>0`. I just like my one line versions (without fancy smansy Array operations ;P) – Hamish Feb 10 '11 at 04:18
1

There are faster ways to do this, but it's the same as you would do in any other procedural language. Notice that if you inject this into a page directly, it'll still show as only one space.

function gimmeSpaces(count){
   var returnValue = '';
     for (int i = 0;i<count;i++){ returnvalue += " ";}
   return returnValue;
}
jcolebrand
  • 15,889
  • 12
  • 75
  • 121
1

Or there's always the array version:

function spaces(n) {
    var a = [ ];
    for(var i = 0; i < n; ++i)
        a.push(' ');
    return a.join('');
}

The basic idea is to build a list of n spaces (a.push(' ')) and then stick them all together at once at the end (a.join('')).

AFAIK, string concatenation (e.g. s += ' ') is slow in some IE versions and the array approach is faster. OTOH, that really shouldn't make much difference in this case so you should go with whatever approach is clearer.

mu is too short
  • 426,620
  • 70
  • 833
  • 800
1

Here's a way that doesn't involve loops:

function getSpaces(n) {
    return new Array(n + 1).join(" ");
}

Alternative, optimistic version (if speed is important, and the max number of spaces you would ever need is known):

function getSpaces(n) {
    return "                 ".substr(-n);
}
Ates Goral
  • 137,716
  • 26
  • 137
  • 190