เราต้องเขียนฟังก์ชัน JavaScript ที่รับสตริง 2 ตัว (str1, str2) และตรวจสอบว่า str1 เริ่มต้นด้วย str2 หรือ ลงท้ายด้วย str2 ถ้าใช่คืนค่า true มิฉะนั้น false
โค้ดตัวอย่าง
const str = 'this is an example string';
const startsOrEndsWith = (str1 = '', str2 = '') => {
if (str2.length > str1.length) return false;
if (str1 === str2) return true;
const { length: l1 } = str1;
const { length: l2 } = str2;
const startPart = str1.substring(0, l2);
const endPart = str1.substring(l1 - l2, l1);
return startPart === str2 || endPart === str2;
};
console.log(startsOrEndsWith(str, 'hel')); // false
console.log(startsOrEndsWith(str, 'ing')); // true
console.log(startsOrEndsWith(str, 'thi')); // true
ผลลัพธ์
false true true
วิธีทันสมัย (ES6+)
// ใช้ startsWith() และ endsWith() - มาตรฐาน อ่านง่าย
const startsOrEndsWithModern = (str1, str2) =>
str1.startsWith(str2) || str1.endsWith(str2);
// รองรับ position parameter ด้วย
const startsOrEndsWithAdvanced = (str1, str2, position) => {
if (position !== undefined) {
return str1.startsWith(str2, position) || str1.endsWith(str2, position + str2.length);
}
return str1.startsWith(str2) || str1.endsWith(str2);
};
คำอธิบายเมธอดเริ่มต้น
str.startsWith(searchString[, position])- ตรวจสอบต้นสตริงstr.endsWith(searchString[, length])- ตรวจสอบท้ายสตริง- ทั้งสองเมธอดคืนค่า boolean และรองรับ position parameter
- Case-sensitive
กรณีพิเศษ
// สตริงว่าง
''.startsWith(''); // true
''.endsWith(''); // true
// str2 ยาวกว่า str1
'abc'.startsWith('abcd'); // false
'abc'.endsWith('abcd'); // false