Finding 1-Based Index of a Character in Alphabets Using JavaScript



Problem

We are required to write a JavaScript function that takes in a lowercase English alphabet character. Our function should return the character’s 1-based index in the alphabets.

Example

Following is the code −

 Live Demo

const char = 'j';
const findCharIndex = (char = '') => {
   const legend = ' abcdefghijklmnopqrstuvwxyz';
   if(!char || !legend.includes(char) || char.length !== 1){
      return -1;
   };
   return legend.indexOf(char);
};
console.log(findCharIndex(char));

Output

10
Updated on: 2021-04-21T06:58:32+05:30

170 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements