Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Nối 2 chuỗi lấy 2 ký tự xen kẽ - JavaScript

Viết hàm nhận 2 chuỗi, trả về chuỗi mới lấy 2 ký tự từ chuỗi 1, 2 ký tự từ chuỗi 2, xen kẽ cho đến hết.

Ví dụ

Chuỗi 1: 'Hello world'

Chuỗi 2: 'How are you btw'

Kết quả: 'HeHollw o arwoe rlyodu btw'

Giải pháp

Mã triển khai:

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

const twiceJoin = (str1 = '', str2 = '') => {
  let res = '', i = 0, j = 0;
  // Xen kẽ lấy 2 ký tự
  while (i < str1.length || j < str2.length) {
    res += str1.slice(i, i+2);
    i += 2;
    res += str2.slice(j, j+2);
    j += 2;
  }
  return res;
};

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

Kết quả

Đầu ra trong console:

HeHollw o arwoe rlyodu btw