Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
How to merge two strings alternatively in JavaScript
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
Advertisements
