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
Add a ment  | 

4 Answers 4

Reset to default 1

There'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