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.