Chúng ta cần viết hàm JavaScript nhận vào hai chuỗi (string1, string2) và xác định string1 có kết thúc bằng string2 hay không.
Ví dụ: "The game is on" với "on" → true; "the game is off" với "of" → false.
Dưới đây là mã:
Ví dụ
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'));Kết quả
Đầu ra trong console sẽ là:
true false