Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Joining two strings with a comma and space between them

Tags:

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;  } 
like image 992
Andrew P Avatar asked Jan 02 '14 11:01

Andrew P


People also ask

How do you concatenate two strings separated by a comma?

To concatenate strings with a separator, add the strings to an array and call the join() method on the array, passing it the separator as a parameter. The join method returns a string, where all array elements are joined using the provided separator. Copied!

Which is the correct way to concatenate 2 strings?

You concatenate strings by using the + operator. For string literals and string constants, concatenation occurs at compile time; no run-time concatenation occurs. For string variables, concatenation occurs only at run time.

How do you concatenate two strings with a space in Python?

Python concatenate strings with space We can also concatenate the strings by using the space ' ' in between the two strings, and the “+” operator is used to concatenate the string with space. To get the output, I have used print(my_str).


1 Answers

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 
like image 167
thefourtheye Avatar answered Sep 18 '22 03:09

thefourtheye