Joining two strings with two words at a time - JavaScript

We are required to write a JavaScript function that takes in two strings, creates and returns a new string with first two characters of first string, next two characters of second string, then first, then second and so on.

For example:

If the strings are:

const str1 = 'Hello world';
const str2 = 'How are you btw';

Then the output should be:

'HeHollw o arwoe rlyodu btw'

Approach

The algorithm alternates between the two strings, taking two characters at a time. When one string is exhausted, it appends the remaining characters from the other string.

Example

Let us write the code for this function:

const str1 = 'Hello world';
const str2 = 'How are you btw';

const twiceJoin = (str1 = '', str2 = '') => {
    let res = '', i = 0, j = 0, temp = '';
    for(let ind = 0; i < str1.length; ind++){
        if(ind % 2 === 0){
            temp = (str1[i] || '') + (str1[i+1] || '')
            res += temp;
            i += 2;
        }else{
            temp = (str2[j] || '') + (str2[j+1] || '')
            res += temp;
            j += 2;
        }
    };
    while(j < str2.length){
        res += str2[j++];
    };
    return res;
};

console.log(twiceJoin(str1, str2));

Output

HeHollw o arwoe rlyodu btw

How It Works

The function uses two pointers i and j to track positions in both strings. The ind counter alternates between strings - even indices take from str1, odd indices from str2. After the main loop, any remaining characters from str2 are appended.

Alternative Implementation

Here's a cleaner version that handles both strings more symmetrically:

const twiceJoinImproved = (str1 = '', str2 = '') => {
    let result = '';
    let i = 0, j = 0;
    let useFirst = true;
    
    while (i < str1.length || j < str2.length) {
        if (useFirst && i < str1.length) {
            result += str1.slice(i, i + 2);
            i += 2;
        } else if (!useFirst && j < str2.length) {
            result += str2.slice(j, j + 2);
            j += 2;
        }
        useFirst = !useFirst;
    }
    
    return result;
};

console.log(twiceJoinImproved('Hello world', 'How are you btw'));

Output

HeHollw o arwoe rlyodu btw

Conclusion

This string joining technique alternates between two strings, taking two characters at a time from each. The key is managing two pointers and handling remaining characters when one string is exhausted.

Updated on: 2026-03-15T23:18:59+05:30

215 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements