 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Twice join of two strings in JavaScript
We are required to write a JavaScript function that takes in two strings; creates and returns a new string with first 2 words of first string, next two words 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 −
const output = 'HeHollw o arwoe rlyodu btw';
Therefore, let’s write the code for this function −
Example
The code for this will be −
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
The output in the console will be −
HeHollw o arwoe rlyodu btw
Advertisements
 