检查字符串是否以其他字符串结尾-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