检查字符串是否以其他字符串结尾 - JavaScript
javascriptweb developmentfront end technologyobject oriented programming更新于 2025/12/30 20:28:17
我们需要编写一个 JavaScript 函数,该函数接受两个字符串,例如 str1 和 str2。该函数应确定 str1 是否以 str2 结尾。我们的函数应在此基础上返回一个布尔值。
这是我们的第一个字符串 −
const str1 = '这只是一个例子';
这是我们的第二个字符串 −
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
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

