Was it helpful?

Question

Trying to get number for each character in string - JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

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"
raja
Published on 30-Sep-2020 18:04:18
Advertisements
Was it helpful?
Not affiliated with Tutorialspoint
scroll top