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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With