Trying to get number for each character in string - 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 = 26

Therefore, if the input is "hello man",

Then the output should be a number for each character −

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

Example

Following is the code −

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

This will produce the following output in console −

"8,5,12,12,15,13,1,14"
Updated on: 2020-09-30T14:34:18+05:30

224 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements