Joining two strings with a comma and space between them

安稳与你 提交于 2020-01-22 05:50:05

问题


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;

}

回答1:


try this:

 function test(str1, str2) {

     var res = str2 + ',' + str1;

     return res;

 }



回答2:


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



回答3:


That's it:

strings = ["str1", "str2"]; 
strings.join(", ");



回答4:


Just add the strings.

res = str1 + ', ' + str2;



回答5:


try this

function test(str1, str2) {

var res = str1+", "+str2;

return res;

}



回答6:


you can easily do this:

function test(str1, str2) {
    return Array.prototype.join.call(arguments, ", ");
}



回答7:


My trick is to use concat() twice (with chaining).

var str1 = "Hello";
var str2 = "world!";
var result = str1.concat(", ").concat(str2);
document.getElementById("demo").innerHTML=result;

Working Demo




回答8:


You can also use concat() with multiple params.

a = 'car'
a.concat(', ', 'house', ', ', 'three')
// "car, house, three"


来源:https://stackoverflow.com/questions/20881950/joining-two-strings-with-a-comma-and-space-between-them

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!