Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print out N spaces in Javascript?

Tags:

javascript

In Javascript, the method to print out using

console.log("this is %s and %s", foo, bar);

works, so it follows some C style, but it doesn't follow

console.log("%*s this is %s and %s", 12, foo, bar);

where the %*s and 12 is to make it print out 12 spaces, as in this question: In Objective-C, how to print out N spaces? (using stringWithCharacters)

Is there a short, quick way to make it work simply in Javascript? (say, without using the sprintf open source library or writing a function to do it?)

Update:, in my case, 12 is actually a variable, such as (i * 4), so that's why it can't be hardcoded spaces inside the string.

like image 877
Jeremy L Avatar asked Oct 01 '12 07:10

Jeremy L


1 Answers

The easiest way would be to use Array.join:

console.log("%s this is %s and %s", Array(12 + 1).join(" "), foo, bar);

Note that you want N + 1 for the array size.


I know you said you dont want functions, but if you do this a lot, an extention method can be cleaner:

String.prototype.repeat = function(length) {
 return Array(length + 1).join(this);
};

This allows you to do:

console.log("%s this is %s and %s", " ".repeat(12), foo, bar);
like image 154
alexn Avatar answered Oct 09 '22 01:10

alexn