16

I would like to know how to convert each alphabetic character entered to a number.

e.g. a=1, b=2 ,c=3 up to z=26

In C I had managed to do something similar, by taking a character input and displaying it as an integer. But I'm not sure how I would do this in JavaScript.

2
  • 1
    Can you show a use case, i.e. how you're getting the character?
    – Teemu
    Jan 10, 2015 at 14:23
  • I am getting the character from an HTML input form, when a button is clicked the page will show the numerical value of the letter.
    – Alex Kom
    Jan 10, 2015 at 14:24

9 Answers 9

62

If I get you right, the other answers are over complicated:

parseInt('a', 36) - 9; // 1
parseInt('z', 36) - 9; // 26
parseInt('A', 36) - 9; // 1
parseInt('Z', 36) - 9; // 26

Now, to answer the question you asked in the comments:

function sumChars(s) {
  var i, n = s.length, acc = 0;
  for (i = 0; i < n; i++) {
    acc += parseInt(s[i], 36) - 9;
  }
  return acc;
}

console.log(sumChars("az"))

However, this notation of an integer is space consuming compared to the positional notation. Compare "baz" in both notations:

sumChars("baz") // 29
parseInt("baz", 36) // 14651

enter image description here

As you can see, the amount of letters is the same, but the base 36 integer is way bigger, in other words, base 36 can store bigger numbers in the same space. Moreover, converting a base 10 integer into base 36 integer is trivial in JavaScript:

(14651).toString(36) // "baz"

Finally, be careful when you want to store the values. Although it sounds counterintuitive, base 2 is more compact than base 36. Indeed, one letter occupies at least 8 bits in memory:

(35).toString(2).length // 6 bits long
(35).toString(36).length * 8 // 8 bits long

Therefore I recommend to use "true" integers for storage, it's easy to get back to base 36 anyway.

4
  • 1
    This is incrediblly simple and straight forward. Thank you!
    – eagercoder
    Jan 17, 2020 at 6:43
  • why minus 9 here parseInt('a', 36) - 9? Jun 2, 2020 at 3:11
  • Hi @KickButtowski :-) Because parseInt('0', 36) gives 0, parseInt('1', 36) gives 1, parseInt('2', 36) gives 2, ..., parseInt('9', 36) gives 9, parseInt('a', 36) gives 10, parseInt('b', 36) gives 11, and so on... But the OP wants 'a' to be 1 :-)
    – user1636522
    Jun 9, 2020 at 9:46
  • @KickButtowski, as a side note, base 36 means that you have 36 digits to write a number, 10 digits from 0 to 9 + 26 digits from a to z. To help you understand how to translate a base 36 number to the same number in base 10, enumerate some natural numbers in both bases side by side: 0(36) = 0(10), ..., 9(36) = 9(10), a(36) = 10(10), b(36) = 11(10), ..., z(36) = 35(10), 10(36) = 10(36) + 0(36) = 36(10) + 0(10) = 36(10), 11(36) = 10(36) + 1(36) = 36(10) + 1(10) = 37(10), ..., 1a(36) = 10(36) + a(36) = 36(10) + 10(10) = 46(10), and so on...
    – user1636522
    Jun 9, 2020 at 10:30
9
var alphabet = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"];
var letter = "h";
var letterPosition = alphabet.indexOf(letter)+1;

EDIT:

Possibility to calculate the letters inside a string, aa=2, ab=3 etc.

function str_split(string, split_length) {
  //  discuss at: http://phpjs.org/functions/str_split/
  // original by: Martijn Wieringa
  // improved by: Brett Zamir (http://brett-zamir.me)
  // bugfixed by: Onno Marsman
  //  revised by: Theriault
  //  revised by: Rafał Kukawski (http://blog.kukawski.pl/)
  //    input by: Bjorn Roesbeke (http://www.bjornroesbeke.be/)
  //   example 1: str_split('Hello Friend', 3);
  //   returns 1: ['Hel', 'lo ', 'Fri', 'end']

  if (split_length == null) {
    split_length = 1;
  }
  if (string == null || split_length < 1) {
    return false;
  }
  string += '';
  var chunks = [],
    pos = 0,
    len = string.length;
  while (pos < len) {
    chunks.push(string.slice(pos, pos += split_length));
  }

  return chunks;
}


function count(string){
    var alphabet = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"];

    var splitted_string = str_split(string);

    var count = 0;
    for (i = 0; i < splitted_string.length; i++) { 
        var letterPosition = alphabet.indexOf(splitted_string[i])+1;
        count = count + letterPosition;
    }
    return count;
}

console.log(count("az")); // returns 27 in the console
6
  • You would need to +1 to the letterPosition as the first array will be 0 so "a"=0, not "a"=1.
    – NewToJS
    Jan 10, 2015 at 14:29
  • As array index starts at 0, it will give 0 for a. var letterPosition = alphabet.indexOf(letter)+1; is better. Jan 10, 2015 at 14:31
  • @ErikVandeVen is there a way to add the letters together using your method? e.g. aaa=3, az=27 etc.
    – Alex Kom
    Jan 10, 2015 at 15:00
  • 2
    Probably, but why should "ab" be 27? Jan 10, 2015 at 15:02
  • I meant az sorry for the confusion.
    – Alex Kom
    Jan 10, 2015 at 15:03
3

In JavaScript characters are not a single byte datatype, so if you want to mimick the workings of C, you need to create a mapping by yourself.

For example using a simple object as a map:

var characters: {
    'a': 1,
    'b': 2,
    ...
}

This way var number = charachters['a']; will set number to 1. The others have provided shorted methods, which are most likely more feasible, this one is mostly aimed for easy understanding.

1

You could do it like this

function convertToNumbers(str){
   var arr = "abcdefghijklmnopqrstuvwxyz".split("");
   return str.replace(/[a-z]/ig, function(m){ return arr.indexOf(m.toLowerCase()) + 1 });
}

What your doing is creating an array of alphabets and then using the callback in String.replace function and returning the respective indexes of the letter +1 as the indices start from 0

1

This will work

"abcdefghijklmnopqrstuvwxyz".split("").forEach(function (a,b,c){ console.log(a.toLowerCase().charCodeAt(0)-96)});


"iloveyou".split("").forEach(function (a,b,c){ console.log(a.toLowerCase().charCodeAt(0)-96)});

9
12
15
22
5
25
15
21
1

You can make an object that maps the values-

function letterValue(str){
    var anum={
        a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7, h: 8, i: 9, j: 10, k: 11, 
        l: 12, m: 13, n: 14,o: 15, p: 16, q: 17, r: 18, s: 19, t: 20, 
        u: 21, v: 22, w: 23, x: 24, y: 25, z: 26
    }
    if(str.length== 1) return anum[str] || ' ';
    return str.split('').map(letterValue);
}

letterValue('zoo') returns: (Array) [26,15,15] ;

letterValue('z') returns: (Number) 26

1

You can just get the ascii value and minus 64 for capital letters.

var letterPlacement = "A".charCodeAt(0) - 64;

Or minus 96 for lower case.

var letterPlacement = "a".charCodeAt(0) - 96;

Or as a nice and tidy one line function that doesn't give a damn about case:

function alphabetifier(letter) {
    return letter.charCodeAt(0) - (letter === letter.toLowerCase() ? 96 : 64);
}      
2
  • but some posts used 97? very confusing :/ Jun 2, 2020 at 3:13
  • Actually its 97 only, but that gives an index so 96 "a".charCodeAt() - 96; or "a".charCodeAt() - 97 + 1; Hoping it sould be clear now. :) Oct 20, 2020 at 11:50
1

you can try this simple function.

#Soln 1.

function createIndecesFromChar() {
  let hash = {};
  for(let n = 1; n <= 26; n++) {
     hash[String.fromCharCode(96+n)] = n;     // in case of lowercase letters;
  }

  return hash;
}

console.log(createIndecesFromChar());

// output 
// { a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7, h: 8, i: 9, j: 10, k: 11, l: 12, m: 13, n: 14, o: 15, p: 16, q: 17, r: 18, s: 19, t: 20, u: 21, v: 22, w: 23, x: 24, y: 25, z: 26 }

#Soln 2. another functional straight forward approach.

const indexedMap = Object.fromEntries(Array.from({ length: 26 }, (_, c) => [String.fromCharCode(97+c), c+1]));

console.log(createIndecesFromChar());

// output - same result as above.
// { a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7, h: 8, i: 9, j: 10, k: 11, l: 12, m: 13, n: 14, o: 15, p: 16, q: 17, r: 18, s: 19, t: 20, u: 21, v: 22, w: 23, x: 24, y: 25, z: 26 }
0

function convertAlpha(ch){
  //ASCII code of a is 97 so subtracting 96 would give 1 and so on
  return ch.charCodeAt(0)-96;
}

console.log(convertAlpha("b")); // returns 2

Similar thing can be done for capital alphabets with a if clause. In case of capital alphabets we would subtract with 64 as ASCII value of 'A' is 65 so 65-64 = 1, and so on for other alphabets.

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.