두 개의 문자열을 받아서 첫 번째 문자열의 처음 두 단어, 두 번째 문자열의 다음 두 단어, 첫 번째 문자열, 두 번째 단어 등으로 새 문자열을 만들고 반환하는 JavaScript 함수를 작성해야 합니다.
예를 들어 -
문자열이 -
인 경우const str1 = 'Hello world'; const str2 = 'How are you btw';
그러면 출력은 다음과 같아야 합니다. -
const output = 'HeHollw o arwoe rlyodu btw';
예시
이 함수의 코드를 작성해 보겠습니다 -
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)); 출력
다음은 콘솔의 출력입니다 -
HeHollw o arwoe rlyodu btw