given input str1 is "abc" and str2 is "def" output should be adbecf and given str1 = "ab" and str2 = "def" output should be adbef
my output has been:
merge('abc','def') "adbecfNaN"
merge('ab','def') "adbeundefinedf"
I have been attempting to filter undefined and NAN, but it's not working.
Here's my code:
function merge (str1, str2) {
var a = str1.split("").filter(Boolean);
var b = str2.split("");
var mergedString = '';
for(var i = 0; i <= a.length && i <= b.length; i++) {
mergedString += a[i] + b[i];
}
return mergedString;
}
Concatenation is the process of appending one string to the end of another string. You concatenate strings by using the + operator. For string literals and string constants, concatenation occurs at compile time; no run-time concatenation occurs.
In JavaScript, we can assign strings to a variable and use concatenation to combine the variable to another string. To concatenate a string, you add a plus sign+ between the strings or string variables you want to connect.
you need to use <
and not <=
in loop condition since array indexes are started from 0. That is why you are getting NaN. you can do something like this:
function merge (str1, str2) {
var a = str1.split("").filter(Boolean);
var b = str2.split("");
var mergedString = '';
for(var i = 0; i < a.length || i < b.length; i++) { //loop condition checks if i is less than a.length or b.length
if(i < a.length) //if i is less than a.length add a[i] to string first.
mergedString += a[i];
if(i < b.length) //if i is less than b.length add b[i] to string.
mergedString += b[i];
}
return mergedString;
}
console.log(merge('abc','def'));
console.log(merge('ab','def'));
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