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; }
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!
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.
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).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With