檢查字串是否以其他字串結尾 - JavaScript


我們需要編寫一個 JavaScript 函式,此函式接收兩個字串,例如 str1 和 str2。該函式應該確定 str1 是否以 str2 結尾。我們的函式應該在此基礎上返回一個布林值。

這是我們的第一個字串 -

const str1 = 'this is just an example';

這是我們的第二個字串 -

const str2 = 'ample';

示例

以下是程式碼 -

const str1 = 'this is just an example';
const str2 = 'ample';
const endsWith = (str1, str2) => {
   const { length } = str2;
   const { length: l } = str1;
   const sub = str1.substr(l - length, length);
   return sub === str2;
};
console.log(endsWith(str1, 'temple'));
console.log(endsWith(str1, str2));

輸出

這將在控制檯中產生以下輸出 -

false
true

更新日期: 2020-09-30

124 次觀看

飛速開展您的職業生涯

透過完成本課程獲得認證

開始
廣告
© . All rights reserved.