How to merge two strings alternatively in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to write a JavaScript function that takes in two. Our function should then return a new array that contains characters alternatively from both the strings.

For example: If the two strings are −

const str1 = 'abc';
const str2 = 'def';

Output

Then the output should be −

const output = 'adbecf';

Example

The code for this will be −

const str1 = 'abc';
const str2 = 'def';
const mergeAlternatively = (str1, str2) => {
   const a = str1.split("").filter(el => !!el);
   const b = str2.split("");
   let mergedString = '';
   for(var i = 0; i < a.length || i < b.length; i++){
      if(i < a.length){
         mergedString += a[i];
      };
      if(i < b.length){
         mergedString += b[i];
      };
   };
   return mergedString;
};
console.log(mergeAlternatively(str1, str2));

Output

The output in the console −

adbecf
raja
Published on 12-Oct-2020 11:16:56
Advertisements