1

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.

Paul Roub
  • 36,322
  • 27
  • 84
  • 93
Koba
  • 1,514
  • 4
  • 27
  • 48

4 Answers4

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;
Paul Roub
  • 36,322
  • 27
  • 84
  • 93
1

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.

Marco Bonelli
  • 63,369
  • 21
  • 118
  • 128
1
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;
guest271314
  • 1
  • 15
  • 104
  • 177
0

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;
Marco Bonelli
  • 63,369
  • 21
  • 118
  • 128