Koba
Koba

Reputation: 1544

Dynamically add spaces between concatenated strings

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.

Upvotes: 1

Views: 14897

Answers (4)

Marco Bonelli
Marco Bonelli

Reputation: 69286

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;

Upvotes: 0

guest271314
guest271314

Reputation: 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;

Upvotes: 1

Marco Bonelli
Marco Bonelli

Reputation: 69286

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.

Upvotes: 1

Paul Roub
Paul Roub

Reputation: 36438

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;

Upvotes: 1

Related Questions