JavaScript 檢查字串1是否以字串2結尾


我們需要編寫一個 JavaScript 函式,該函式接收兩個字串,比如 string1 和 string2,並確定 string1 是否以 string2 結尾。

例如,

"The game is on"
Here, "on" should return true

儘管

"the game is off"
Above, “of" should return 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

更新於:31-8-2020

95 檢視

開啟您的 職業生涯

完成課程以獲得認證

開始
廣告
© . All rights reserved.