JavaScript 检查 string1 是否以 strings2 结尾
javascriptweb developmentobject oriented programming更新于 2025/10/25 0:44:17
我们需要编写一个 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
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

