Check if string ends with desired character in JavaScript



We are required to write a JavaScript function that takes in a string as the first argument and a single character as the second argument.

The function should determine whether the string specified by the first argument ends with the character specified by the second argument or not. The only condition is that we have to do this without using any ES6 or library methods.

Example

Following is the code −

const str = 'This is a string';
const checkEnding = (str = '', char = '') => {
   // helper function to grab the last character of the string
   const getLast = (str = '') => {
      const { length } = str;
      return str[length - 1];
   };
   return getLast(str) === char;
};
console.log(checkEnding(str, 'g'))
console.log(checkEnding(str, 'h'))

Output

Following is the output on console −

true
false

Advertisements