We are required to write a JavaScript function that takes in two strings say, str1 and str2. The function should determine whether or not str1 ends with str2. Our function should return a boolean on this basis.
Here’s our 1st string −
const str1 = 'this is just an example';
Here’s our 2nd string −
const str2 = 'ample';
Example
Following is the code −
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));Output
This will produce the following output in console −
false true