แนวคิดในที่นี้คือการรับสตริงสองสตริงเป็นอินพุตและคืนค่า จริง หาก a เป็นสตริงย่อยของ b หรือ b เป็นสตริงย่อยของ a ไม่เช่นนั้นจะคืนค่าเท็จ
ตัวอย่างเช่น −
isSubstr(‘hello’, ‘hello world’) // true isSubstr(‘can I use’ , ‘I us’) //true isSubstr(‘can’, ‘no we are’) //false
ดังนั้นในฟังก์ชัน เราจะตรวจสอบสตริงที่ยาวกว่า อันที่มีอักขระมากกว่า และตรวจสอบว่าอีกอันเป็นสตริงย่อยหรือไม่
นี่คือรหัสสำหรับการทำเช่นนั้น -
ตัวอย่าง
const str1 = 'This is a self-driving car.';
const str2 = '-driving c';
const str3 = '-dreving';
const isSubstr = (first, second) => {
if(first.length > second.length){
return first.includes(second);
}
return second.includes(first);
};
console.log(isSubstr(str1, str2));
console.log(isSubstr(str1, str3a)); ผลลัพธ์
ผลลัพธ์ในคอนโซลจะเป็น -
true false