เราต้องเขียนฟังก์ชันที่รับสตริงสองตัว str1 และ str2 ฟังก์ชันควรตรวจสอบว่า str1 ลงท้ายด้วย str2 หรือไม่ และคืนค่า boolean
สตริงแรก: 'this is just an example'
สตริงที่สอง: 'ample'
ตัวอย่าง
โค้ดต่อไปนี้เป็นตัวอย่าง:
const str1 = 'this is just an example';
const str2 = 'ample';
const endsWith = (str1, str2) => {
const { length } = str2;
const { length: l } = str1;
const sub = str1.substr(l - length, length);
return sub === str2;
};
console.log(endsWith(str1, 'temple'));
console.log(endsWith(str1, str2));ผลลัพธ์
จะแสดงผลในคอนโซลดังนี้:
false true