Search code examples
javascriptstring-concatenation

Concatenating numbers as string in Javascript


myCoolObject {
  a: 0
  b: 12
  c: 24
}

I want to concatenate a, b and c so that they look like a unique string "a-b-c" (or "0-12-24" in the example).

a, b and c will always represent numbers. Converting each one of them from int to string require a lot of code: I'd just use sprintf() if I were in PHP or C, but how can I do this in JS without using toString() for each parameter and writing too much code?

Whole code:

var pickedDate = this.getSelectedDay().year.toString() + "-" + this.getSelectedDay().month.toString() + this.getSelectedDay().day.toString();

Seriously? Isn't there any more efficient way of doing this in js?


Solution

  • var myCoolString = myCoolObject.a + '-' + myCoolObject.b + '-' + myCoolObject.c;
    

    EDIT:

    With ES6, you can use template strings to interpolate numbers into strings:

    let myCoolString = `${myCoolObject.a}-${myCoolObject.b}-${myCoolObject.c}`;
    

    Try it:

    var myCoolObject = {
      a: 0,
      b: 12,
      c: 24
    };
    
    var myCoolString = myCoolObject.a + '-' + myCoolObject.b + '-' + myCoolObject.c;
    
    console.log(typeof myCoolString);
    console.log(myCoolString);