เราต้องเขียนฟังก์ชัน JavaScript ที่รับสตริงสองตัวและตรวจสอบว่าสตริงแรกเริ่มต้นด้วยสตริงที่สองหรือไม่
เช่น สองสตริงคือ: "Disaster management report" และ "Disas" ฟังก์ชันควรคืนค่า true
มาเขียนโค้ดสำหรับฟังก์ชันนี้กัน
ตัวอย่าง
const first = 'The game is on';
const second = 'The';
const startsWith = (first, second) => {
const { length } = second;
const { length: l } = first;
const sub = first.substr(0, length);
return sub === second;
};
console.log(startsWith(first, second));
ผลลัพธ์
ผลลัพธ์ในคอนโซลจะเป็นดังนี้
true