Check whether a string ends with some other string - JavaScript



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
Updated on: 2020-09-30T13:50:14+05:30

166 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements