How to convert letters to numbers with Javascript?

You can get a codepoint* from any index in a string using String.prototype.charCodeAt. If your string is a single character, you’ll want index 0, and the code for a is 97 (easily obtained from JavaScript as 'a'.charCodeAt(0)), so you can just do:

s.charCodeAt(0) - 97

And in case you wanted to go the other way around, String.fromCharCode takes Unicode codepoints* and returns a string.

String.fromCharCode(97 + n)

* not quite


If you want to be able to handle Excel like letters past 26 like AA then you can use the following function adapted from this question:

function convertLetterToNumber(str) {
  var out = 0, len = str.length;
  for (pos = 0; pos < len; pos++) {
    out += (str.charCodeAt(pos) - 64) * Math.pow(26, len - pos - 1);
  }
  return out;
}

Demo in Stack Snippets:

function convertLetterToNumber(str) {
  var out = 0, len = str.length;
  for (pos = 0; pos < len; pos++) {
    out += (str.charCodeAt(pos) - 64) * Math.pow(26, len - pos - 1);
  }
  return out;
}

var testCase = ["A","B","C","Z","AA","AB","BY"];

var converted = testCase.map(function(obj) {
  return {
    letter: obj,
    number: convertLetterToNumber(obj)
  };

});

console.table(converted);

This is short, and supports uppercase and lowercase.

const alphaVal = (s) => s.toLowerCase().charCodeAt(0) - 97 + 1

Sorry, I thought it was to go the other way.

Try this instead:

var str = "A";
var n = str.charCodeAt(0) - 65;

Tags:

Javascript