
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
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 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';
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
Following is the output in the console −
HeHollw o arwoe rlyodu btw
- Related Articles
- Construct objects from joining two strings JavaScript
- Function to check two strings and return common words in JavaScript
- Joining two Arrays in Javascript
- Common Words in Two Strings in Python
- Joining two hash tables in Javascript
- Adding two values at a time from an array - JavaScript
- Python program to find uncommon words from two Strings
- Difference between two strings JavaScript
- How to extract the strings between two words in R?
- Differences in two strings in JavaScript
- Python program to remove words that are common in two Strings
- How to add two strings with a space in first string in JavaScript?
- How to compare two strings in the current locale with JavaScript?
- Find the dissimilarities in two strings - JavaScript
- Finding shared element between two strings - JavaScript

Advertisements