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
-
Economics & Finance
How to merge two strings alternatively in JavaScript
In JavaScript, merging two strings alternatively means combining characters from both strings one by one. This creates a new string where characters alternate between the first and second input strings.
For example, if we have two strings:
const str1 = 'abc';
const str2 = 'def';
console.log('String 1:', str1);
console.log('String 2:', str2);
String 1: abc String 2: def
The expected output should be:
adbecf
Using Loop-Based Approach
Here's a function that merges two strings alternatively by iterating through both strings simultaneously:
const str1 = 'abc';
const str2 = 'def';
const mergeAlternatively = (str1, str2) => {
let mergedString = '';
const maxLength = Math.max(str1.length, str2.length);
for (let i = 0; i < maxLength; i++) {
if (i < str1.length) {
mergedString += str1[i];
}
if (i < str2.length) {
mergedString += str2[i];
}
}
return mergedString;
};
console.log(mergeAlternatively(str1, str2));
adbecf
Using Array Methods
An alternative approach using array methods for a more functional programming style:
const mergeWithArrayMethods = (str1, str2) => {
const maxLength = Math.max(str1.length, str2.length);
return Array.from({ length: maxLength }, (_, i) => {
return (str1[i] || '') + (str2[i] || '');
}).join('');
};
const str1 = 'hello';
const str2 = 'world';
console.log('Result:', mergeWithArrayMethods(str1, str2));
Result: hweolrllod
Handling Different String Lengths
The function works correctly even when strings have different lengths:
const mergeAlternatively = (str1, str2) => {
let mergedString = '';
const maxLength = Math.max(str1.length, str2.length);
for (let i = 0; i < maxLength; i++) {
if (i < str1.length) {
mergedString += str1[i];
}
if (i < str2.length) {
mergedString += str2[i];
}
}
return mergedString;
};
// Different length strings
console.log('Short + Long:', mergeAlternatively('ab', 'defgh'));
console.log('Long + Short:', mergeAlternatively('abcde', 'xy'));
Short + Long: adbefgh Long + Short: axbycde
Comparison
| Method | Readability | Performance | Best For |
|---|---|---|---|
| Loop-based | High | Good | Simple implementation |
| Array methods | Medium | Moderate | Functional programming style |
Conclusion
The loop-based approach provides a clear and efficient solution for merging strings alternatively. It handles strings of different lengths gracefully and maintains good performance for most use cases.
