Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

การรวมสองสตริงทีละสองตัวอักษร - JavaScript

ฟังก์ชันนี้รวมสองสตริงโดยสลับกันทีละ 2 ตัวอักษร: 2 ตัวจากสตริงแรก, 2 ตัวจากสตริงที่สอง, สลับไปเรื่อยๆ

ตัวอย่าง

str1 = 'Hello world'
str2 = 'How are you btw'
// 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;

  for (let ind = 0; i < str1.length; ind++) {
    if (ind % 2 === 0) {
      // หยิบ 2 ตัวจาก str1
      res += (str1[i] || '') + (str1[i + 1] || '');
      i += 2;
    } else {
      // หยิบ 2 ตัวจาก str2
      res += (str2[j] || '') + (str2[j + 1] || '');
      j += 2;
    }
  }

  // เหลือ str2 ให้ต่อท้าย
  while (j < str2.length) {
    res += str2[j++];
  }

  return res;
};

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

ผลลัพธ์

HeHollw o arwoe rlyodu btw

หมายเหตุ: โค้ดทำงานระดับตัวอักษร (character) ไม่ใช่ระดับคำ (word)