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

JavaScript ตรวจสอบว่าสตริง 1 จบด้วยสตริง 2 หรือไม่


เราต้องเขียนฟังก์ชัน JavaScript ที่รับสตริงสองตัว คือ string1 และ string2 และกำหนดว่า string1 จบด้วย string2 หรือไม่

เช่น "The game is on" ที่นี่ "on" ควรคืนค่า true

ในขณะที่ "the game is off" ด้านบน "of" ควรคืนค่า 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