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.

2
  • 1
    Something like [name, age, "thing"].join(" ") ? That's not exactly cleaner though. Commented Aug 5, 2014 at 16:46
  • possible duplicate of Repeat Character N Times Commented Aug 5, 2014 at 17:02

4 Answers 4

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;
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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;

Comments

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.