Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to merge two strings alternatively in javascript?

Tags:

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;

}
like image 247
raj jar Avatar asked Sep 06 '17 05:09

raj jar


People also ask

Which method will you use to combine two strings into one text?

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.

How do you concatenate strings in JavaScript?

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.


1 Answers

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'));
like image 66
Dij Avatar answered Oct 11 '22 12:10

Dij