Skip to content Skip to sidebar Skip to footer

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 repre

Solution 1:

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);

Solution 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"

Solution 3:

  1. Try sprintf() for JavaScript.

  2. Add new method to string

    if (!String.prototype.format) {
    String.prototype.format = function() {
       var args = arguments;
       returnthis.replace(/{(\d+)}/g, function(match, number) { 
          returntypeof args[number] != 'undefined'
           ? args[number]
            : match
          ;
       });
      };
    }
    
    "{0} - {1} - {2}".format(myCoolObject.a, myCoolObject.b,myCoolObject.c)
    

Solution 4:

Without much code it looks perfect here is the demo

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

var r="";

// iterate through all object propertiesfor (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));

Solution 5:

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) { 
        returnString(args[$1])
    })
}

and then:

var pickedDate = format('{0}-{1}-{2}', 
    this.getSelectedDay().year, 
    this.getSelectedDay().month, 
    this.getSelectedDay().day)

Post a Comment for "Concatenating Numbers As String In Javascript"