Reputation: 1597
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;
}
Upvotes: 30
Views: 140529
Reputation: 122906
Here is a more generic function to concat a variable amount of string values with a separator. Includes error (type) checking.
const [str1, str2, str3, str4] = ["str1", "str2", "str3", "str4"];
console.log(concatStringsWithSeparator(str1, str2));
console.log(concatStringsWithSeparator(str1, str4, str3, str2));
console.log(concatStringsWithSeparator("!#><", str2, str1, str4));
console.log(concatStringsWithSeparator("!# => ", str1, str4, str3, str2));
console.log(concatStringsWithSeparator(`will be error`, 23, `etc`));
function concatStringsWithSeparator(...strings) {
if ( !isArrayOfString(strings) ) {
throw new TypeError(`...strings != Array<string>(>1)`);
}
let separator = `, `;
if (strings[0].startsWith(`!#`)) {
separator = strings[0].slice(2);
strings = strings.slice(1);
}
return strings.join(separator);
function isArrayOfString(input) {
return input?.constructor === Array
&& strings.length > 1
&& !strings.find(s => s?.constructor !== String);
}
}
.as-console-wrapper {
max-height: 100% !important;
}
Upvotes: 0
Reputation: 670
It feels like a competition of evil geniuses. Let me participate:
const str1 = 'foo, bar';
const str2 = 'buzz, bux';
const mergedString = str1.split(',').concat(str2.split(',')).join(', ');
console.log(mergedString); // 'foo, bar, buzz, bux'
Upvotes: 0
Reputation: 21
For whoever's dealing with variables that may or may not be empty, and needs to add spacing only when necessary, this solution works for me:
let string1 = "tipo"
let string2 = ""
let string3 = "HGT"
[string1, string2, string3].filter(Boolean).join(" ")
Result:
tipo HGT
(notice the lack of the extra spaces)
Upvotes: 1
Reputation: 341
We should also consider the false case, if values are not present.
function joinString(str1, str2, delimiter) {
const first = str1 || ''
const second = str1 && str2 ? delimiter : ''
const third = str2 || ''
return `${first}${second}${third}`
}
console.log(joinString('A', 'B', ' ')) // Output A B
console.log(joinString('A', 'B', ',')) // Output A,B
console.log(joinString('', 'B', ' ')) // Output B
console.log(joinString('A', '', ' ')) // Output A
console.log(joinString('', '', ',')) // Output
console.log(joinString(null, '', ',')) // Output
We can write the function code in one line also but for more readability divided into small part
Other solution but it will give error if your input is empty. so always check for string is valid or not.
function joinString(str1, str2, delimiter) {
return str1.concat(str1 && str2 ? delimiter : '').concat(str2)
}
console.log(joinString('A', 'B', ' ')) // Output A B
console.log(joinString('A', 'B', ',')) // Output A,B
console.log(joinString('', 'B', ' ')) // Output B
console.log(joinString('A', '', ' ')) // Output A
console.log(joinString('', '', ',')) // Output
console.log(joinString(null, '', ',')) // Output Error
Upvotes: 0
Reputation: 1
There are a lot of way to do this:
var str1 = "Hello";
const str2 = "world!";
const result1 = str1+", "+str2;
const result2 = `${str1}, ${str2}`;
const result3 = str1.concat(", ").concat(str2);
const strings = [str1, str2];
const result4 = strings.join(", ")
Upvotes: 0
Reputation: 47
Google led us here, and apparently nobody mentions what we were after:
function metJoinStrings(varpString1, varpString2, varpSeparator) {
return varpString1 + (varpString1 === '' ? '' : varpSeparator) + varpString2;
}
With this approach, the end result is presentable as expected, and consequently splittable afterwards. IMPORTANT: one could want to verify or manage the presence of 'varpSeparator' in the source strings, and act accordingly.
Also, parameter type validation should be added.
Upvotes: 1
Reputation: 848
You can also use concat()
with multiple params.
a = 'car'
a.concat(', ', 'house', ', ', 'three')
// "car, house, three"
Upvotes: 2
Reputation: 15501
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;
Upvotes: 1
Reputation: 12961
you can easily do this:
function test(str1, str2) {
return Array.prototype.join.call(arguments, ", ");
}
Upvotes: 2
Reputation: 1260
try this:
function test(str1, str2) {
var res = str2 + ',' + str1;
return res;
}
Upvotes: 22
Reputation: 9635
try this
function test(str1, str2) {
var res = str1+", "+str2;
return res;
}
Upvotes: 1
Reputation: 239453
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
Upvotes: 52