เราจำเป็นต้องเขียนฟังก์ชัน JavaScript ที่รับสองสตริง กล่าวคือ string1 และ string2 และกำหนดว่า string1 ลงท้ายด้วย string2 หรือไม่
ตัวอย่างเช่น −
"The game is on" Here, "on" should return true
ในขณะที่
"the game is off" Above, “of" should return false
มาเขียนโค้ดสำหรับฟังก์ชันนี้กัน −
ตัวอย่าง
const first = 'The game is on';
const second = ' on';
const endsWith = (first, second) => {
const { length } = second;
const { length: l } = first;
const sub = first.substr(l - length, length);
return sub === second;
};
console.log(endsWith(first, second));
console.log(endsWith(first, ' off')); ผลลัพธ์
ผลลัพธ์ในคอนโซลจะเป็น -
true false