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

การสลับตัวอักษรแรกของคำในสตริงใน JavaScript


ปัญหา

เราต้องเขียนฟังก์ชัน JavaScript ที่รับสตริงที่มีคำทั้งหมด 2 คำ ฟังก์ชันควรสร้างและคืนค่าสตริงใหม่ที่ตัวอักษรแรกของคำทั้งสองถูกสลับกัน

ตัวอย่าง

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

const str = 'hello world';
const interchangeChars = (str = '') => {
  const [first, second] = str.split(' ');
  const fChar = first[0];
  const sChar = second[0];
  const newFirst = sChar + first.substring(1, first.length);
  const newSecond = fChar + second.substring(1, second.length);
  const newStr = newFirst + ' ' + newSecond;
  return newStr;
};
console.log(interchangeChars(str));

ผลลัพธ์

ผลลัพธ์ในคอนโซล:

wello horld