Check for specific beginning or ending letters in a JavaScript function


We are required to write a JavaScript function that takes in two strings. Let’s call them str1 and str2.

Our function should check either str1 starts with str2 or it ends with str2. If this is the case, we should return true otherwise we should return false.

Example

Following is the code −

const str = 'this is an example string';
const startsOrEndsWith = (str1 = '', str2 = '') => {
   if(str2.length > str1.length){
      return false;
   };
   if(str1 === str2){
      return true;
   };
   const { length: l1 } = str1;
   const { length: l2 } = str2;
   const startPart = str1.substring(0, l2);
   const endPart = str1.substring(l1 - l2, l1);
   return startPart === str2 || endPart === str2;
};
console.log(startsOrEndsWith(str, 'hel'));
console.log(startsOrEndsWith(str, 'ing'));
console.log(startsOrEndsWith(str, 'thi'));

Output

Following is the output on console −

false
true
true

Updated on: 10-Dec-2020

37 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements