admin管理员组文章数量:1406018
I am wondering if it is possible to dynamically add space between two concatenated strings or integers. For example, here is simply concatenating a string and an integer:
var name = "Bruce"
var age = 14
name + " " + age
=> 'Bruce 14'
I would like the space between name and age be dynamic. e.g.:
var name = "Bruce"
var age = 14
var numberOfSpaces = something
name + 4 spaces + age
=> 'Bruce 14'
One of the use cases is drawing bar charts in dc.js where I can put name at the bottom and the value at the top of the bar. But this is unrelated. I am just curious if there is a method.
I am wondering if it is possible to dynamically add space between two concatenated strings or integers. For example, here is simply concatenating a string and an integer:
var name = "Bruce"
var age = 14
name + " " + age
=> 'Bruce 14'
I would like the space between name and age be dynamic. e.g.:
var name = "Bruce"
var age = 14
var numberOfSpaces = something
name + 4 spaces + age
=> 'Bruce 14'
One of the use cases is drawing bar charts in dc.js where I can put name at the bottom and the value at the top of the bar. But this is unrelated. I am just curious if there is a method.
Share Improve this question edited Aug 5, 2014 at 17:00 Paul Roub 36.5k27 gold badges86 silver badges95 bronze badges asked Aug 5, 2014 at 16:44 KobaKoba 1,5444 gold badges28 silver badges49 bronze badges 2-
1
Something like
[name, age, "thing"].join(" ")
? That's not exactly cleaner though. – Casey Falk Commented Aug 5, 2014 at 16:46 - possible duplicate of Repeat Character N Times – Paul Roub Commented Aug 5, 2014 at 17:02
4 Answers
Reset to default 1There's a proposed repeat()
method, but it's implemented almost nowhere.
Meanwhile, you can write your own:
function repeatstr(ch, n) {
var result = "";
while (n-- > 0)
result += ch;
return result;
}
var name = "Bruce"
var age = 14
var numberOfSpaces = 4
var fullName = name + repeatstr(" ", numberOfSpaces) + age;
You can create your own function to do it:
function spaces(x) {
var res = '';
while(x--) res += ' ';
return res;
}
var name = "Bruce";
var age = 14;
name + spaces(4) + age;
> "Bruce 14"
I think this is the prettiest and easiest way.
var s = function(n) {return new Array(n + 1).join(",").replace(/,/g," ")};
var name = "Bruce";
var age = 14;
var numberOfSpaces = 4;
name + s(numberOfSpaces) + age;
Update! The String.prototype.repeat()
has been supported by all major browsers for quite some time now.
You can just do:
var name = "Bruce";
var age = 14;
name + ' '.repeat(4) + age;
本文标签: javascriptDynamically add spaces between concatenated stringsStack Overflow
版权声明:本文标题:javascript - Dynamically add spaces between concatenated strings - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744336331a2601210.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论