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

ต่อสตริงข้ามตัวซ้ำที่ต่อกัน - JavaScript

ต่อสตริงสองสตริง แต่ถ้าตัวอักษรท้ายของสตริงแรก และตัวแรกของสตริงที่สองเหมือนกัน ให้ตัดทิ้งหนึ่งตัว

ตัวอย่าง

'Food' + 'dog' = 'Foodog'  // 'd' ซ้ำกัน ตัดทิ้งหนึ่งตัว

ตัวอย่างโค้ด

const str1 = 'Food';
const str2 = 'dog';

const concatenateStrings = (str1, str2) => {
  const l1 = str1.length;
  const l2 = str2.length;
  
  if (str1[l1 - 1] !== str2[0]) {
    return str1 + str2;
  }
  
  return str1 + str2.slice(1);
};

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

ผลลัพธ์

Foodog

กรณีทดสอบเพิ่มเติม

console.log(concatenateStrings('Hello', 'World'));  // HelloWorld
console.log(concatenateStrings('cat', 'tiger'));    // catiger
console.log(concatenateStrings('abc', 'def'));      // abcdef