Joining two strings with a comma and space between them

Andrew P picture Andrew P · Jan 2, 2014 · Viewed 84.6k times · Source

I have been given the two strings "str1" and "str2" and I need to join them into a single string. The result should be something like this: "String1, String 2". The "str1" and "str2" variables however do not have the ", ".

So now for the question: How do I join these strings while having them separated by a comma and space?

This is what I came up with when I saw the "task", this does not seperate them with ", " though, the result for this is “String2String1”.

function test(str1, str2) {

    var res = str2.concat(str1);

    return res;

}

Answer

thefourtheye picture thefourtheye · Jan 2, 2014

Simply

return str1 + ", " + str2;

If the strings are in an Array, you can use Array.prototype.join method, like this

var strings = ["a", "b", "c"];
console.log(strings.join(", "));

Output

a, b, c