3
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?

Saturnix
  • 10,130
  • 17
  • 64
  • 120

5 Answers5

6
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);
rink.attendant.6
  • 44,500
  • 61
  • 101
  • 156
  • they're numbers: wouldn't js try to sum them? – Saturnix Jun 06 '13 at 15:15
  • 3
    @Saturnix Because there's a string being concatenated in between. If you just wanted to concatenate them (without characters in between), you could just use `var str = "" + myCoolObject.a + myCoolObject.b + myCoolObject.c;`. As soon as a string is encountered, concatenation will happen, not addition. If addition is needed, parentheses can be used – Ian Jun 06 '13 at 15:15
  • I added a jsFiddle example to demonstrate. – rink.attendant.6 Jun 06 '13 at 15:18
2

how can I do this in JS without [...] writing too much code?

If you know all of your numbers are positive, you can write even less code to achieve the same as we know JavaScript executes left-to-right.

var obj = {a: 0, b: 12, c: 24}; /* define object
String + Number = String
                  String + Number = String
                                    String + Number = String
String + Number + Number + Number     = String    */
  ''   +  obj.a + -obj.b + -obj.c; // = "0-12-24"

The - were inserted because String + -Number = "String-Number", e.g.

'AK' + -47 // "AK-47"
Paul S.
  • 64,864
  • 9
  • 122
  • 138
  • +1 I don't know why this has been downvoted - looks like a legit answer to me. – Saturnix Jun 06 '13 at 15:45
  • legit okay but how is anyone supposed to maintain this code? You save two quotation marks and one plus sign compared to rink's answer and in exchange readability takes a huge hit. – Joooeey Jan 31 '18 at 21:21
1
  1. Try sprintf() for JavaScript.

  2. Add new method to string

    if (!String.prototype.format) {
    String.prototype.format = function() {
       var args = arguments;
       return this.replace(/{(\d+)}/g, function(match, number) { 
          return typeof args[number] != 'undefined'
           ? args[number]
            : match
          ;
       });
      };
    }
    
    "{0} - {1} - {2}".format(myCoolObject.a, myCoolObject.b,myCoolObject.c)
    
Igor S.
  • 3,332
  • 1
  • 25
  • 33
  • 1
    Please link to the [original code](http://stackoverflow.com/a/4673436/989121) instead of copypasting it. – georg Jun 06 '13 at 15:34
1

This is mostly done with Array.join:

var pickedDate = [
    this.getSelectedDay().year, 
    this.getSelectedDay().month, 
    this.getSelectedDay().day
].join("-")

Although I personally prefer a small utility function similar to pythonic format():

format = function(fmt /*, args */) {
    var args = [].slice.call(arguments, 1);
    return fmt.replace(/{(\d+)}/g, function($0, $1) { 
        return String(args[$1])
    })
}

and then:

var pickedDate = format('{0}-{1}-{2}', 
    this.getSelectedDay().year, 
    this.getSelectedDay().month, 
    this.getSelectedDay().day)
georg
  • 211,518
  • 52
  • 313
  • 390
1

Without much code it looks perfect here is the demo

myObj = {
  a: 0,
  b: 12,
  c: 24
}; 

var r="";

// iterate through all object properties
for (var p in myObj) 
{
    //concatenate it
    r+=myObj[p]+"-";
}

//remove the last dash
r=r.substring(0,r.length-1);

alert(r.substring(0,r.length-1));
Nick
  • 4,192
  • 1
  • 19
  • 30