Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

เปรียบเทียบสองประโยคคำต่อคำใน JavaScript คืนค่าว่าเป็น substring ของกันหรือไม่


แนวคิดที่นี่คือรับสตริงสองตัวเป็นอินพุต และคืนค่า true ถ้า a เป็น substring ของ b หรือ b เป็น substring ของ a มิฉะนั้นคืนค่า false

ตัวอย่าง −

isSubstr('hello', 'hello world') // true isSubstr('can I use', 'I us') //true isSubstr('can', 'no we are') //false

ดังนั้น ในฟังก์ชันเราจะตรวจสอบสตริงที่ยาวกว่า ตัวที่มีตัวอักษรมากกว่า และตรวจสอบว่าอีกตัวเป็น substring ของมันหรือไม่

โค้ดสำหรับทำเช่นนี้ −

ตัวอย่าง

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