Replace a letter with its alphabet position JavaScript

JavascriptWeb DevelopmentObject Oriented Programming

We are required to write a function that takes in a string, trims it off any whitespaces, converts it to lowercase and returns an array of numbers describing corresponding characters positions in the english alphabets, any whitespace or special character within the string should be ignored.

For example −

Input → ‘Hello world!’
Output → [8, 5, 12, 12, 15, 23, 15, 18, 12, 4]

The code for this will be −

Example

const str = 'Hello world!';
const mapString = (str) => {
   const mappedArray = [];
   str
   .trim()
   .toLowerCase()
   .split("")
   .forEach(char => {
      const ascii = char.charCodeAt();
      if(ascii >= 97 && ascii <= 122){
         mappedArray.push(ascii - 96);
      };
   });
   return mappedArray;
};
console.log(mapString(str));

Output

The output in the console will be −

[
   8, 5, 12, 12, 15,
   23, 15, 18, 12, 4
]
raja
Published on 20-Aug-2020 06:13:28
Advertisements