Mapping string to Numerals in JavaScript


We are required to write a JavaScript function that takes in a string. It should print out each number for every corresponding letter in the string.

For example:

a = 1
b = 2
c = 3
d = 4
e =5
.
.
.
y = 25
z = 25

Note: Remove any special characters and spaces.

So, if the input is −

"hello man"

Then the output should be −

"8,5,12,12,15,13,1,14"

Example

The code for this will be −

const str = 'hello man';
const charPosition = str => {
   str = str.split('');
   const arr = [];
   const alpha = /^[A-Za-z]+$/;
   for(i=0; i < str.length; i++){
      if(str[i].match(alpha)){
         const num = str[i].charCodeAt(0) - 96;
         arr.push(num);
      }else{
         continue;
      };
   };
   return arr.toString();
}
console.log(charPosition(str));

Output

The output in the console will be −

"8,5,12,12,15,13,1,14"

Updated on: 22-Oct-2020

571 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements