最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to print out N spaces in Javascript? - Stack Overflow

programmeradmin6浏览0评论

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.

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.

Share Improve this question edited May 23, 2017 at 12:32 CommunityBot 11 silver badge asked Oct 1, 2012 at 7:35 Jeremy LJeremy L 3,8106 gold badges43 silver badges63 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 16

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);

As of 2020 and probably earlier, you can use ' '.repeat(12):

console.log(`${' '.repeat(12)}hello`);
console.log(`${' '.repeat(3)}hello`);

发布评论

评论列表(0)

  1. 暂无评论