ปัญหา
เราจำเป็นต้องเขียนฟังก์ชัน JavaScript ที่รับสตริงที่มีคำสองคำพอดี
ฟังก์ชันของเราควรสร้างและส่งคืนสตริงใหม่โดยที่ตัวอักษรตัวแรกของคำจะสลับกัน
ตัวอย่าง
ต่อไปนี้เป็นรหัส -
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