How to convert letters to numbers with Javascript?

Javascript

Javascript Problem Overview


How could I convert a letter to its corresponding number in JavaScript?

For example:

a = 0
b = 1
c = 2
d = 3

I found this question on converting numbers to letters beyond the 26 character alphabet, but it is asking for the opposite.

Is there a way to do this without a huge array?

Javascript Solutions


Solution 1 - 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

Solution 2 - Javascript

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

Try this instead:

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

Solution 3 - Javascript

This is short, and supports uppercase and lowercase.

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

Solution 4 - Javascript

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);

Solution 5 - Javascript

You might assign 1 to 'a', instead of 0, to make it easy to skip (or include) punctuation, numbers or capital letters.

function a1(txt, literal){
	if(!literal) txt= txt.toLowerCase();
	return txt.split('').map(function(c){
		return 'abcdefghijklmnopqrstuvwxyz'.indexOf(c)+1 || (literal? c: '');
	}).join(' ');
}

var str= 'Hello again, world!';

/*  a1(str,'literal')>>value: (String)
H 5 12 12 15   1 7 1 9 14 ,   23 15 18 12 4 !
*/


/*  a1(str) >>value: (String)
8 5 12 12 15  1 7 1 9 14   23 15 18 12 4 
*/

Solution 6 - Javascript

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

Solution 7 - Javascript

You can use this numerical value calculator-it adds up all letter values- for any string (Not Case Sensitive):

function getSum(total,num) {return total + num};
function val(yazı,harf,değer){ rgxp = new RegExp(değer,'gim'); text = yazı.toLowerCase();
if (text.indexOf(harf) > -1){ sonuc = text.split(harf).join(değer).match(rgxp).map(Number).reduce(getSum) }else{ sonuc=0 };
return sonuc;}

String.prototype.abjad = function() {
a = val(this,'a','1'); b = val(this,'b','2'); c = val(this,'c','3'); ç = val(this,'ç','4'); d = val(this,'d','5');
e = val(this,'e','6'); f = val(this,'f','7'); g = val(this,'g','8'); ğ = val(this,'ğ','9'); h = val(this,'h','10');
ı = val(this,'ı','11'); i = val(this,'i','12'); j = val(this,'j','13'); k = val(this,'k','14'); l = val(this,'l','15');
m = val(this,'m','16'); n = val(this,'n','17'); o = val(this,'o','18'); ö = val(this,'ö','19'); p = val(this,'p','20');
r = val(this,'r','21'); s = val(this,'s','22'); ş = val(this,'ş','23'); t = val(this,'t','24'); u = val(this,'u','25');
ü = val(this,'ü','26'); v = val(this,'v','27'); y = val(this,'y','28'); z = val(this,'z','29');
return a+b+c+ç+d+e+f+g+ğ+h+ı+i+j+k+l+m+n+o+ö+p+r+s+ş+t+u+ü+v+y+z
};

Ask();
function Ask() {
    text = prompt("Please enter your text");
    if (text != null) {
    alert("Gematrical value is: " + text.abjad())
    document.getElementById("result").innerHTML = text.abjad();
    }
}

Gematrical value is: <p id="result"></p>

https://jsfiddle.net/nonidentified/0xydecze/1/

Solution 8 - Javascript

I used:

let a = 'dev';
let encode = '';
for (let i = 0; i < a.length; i++) {
  let x = a.slice(i, i+1);
  encode += x.charCodeAt(0);
  
}
console.log(encode);

And result return: 100101118

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionFizzixView Question on Stackoverflow
Solution 1 - JavascriptRy-View Answer on Stackoverflow
Solution 2 - JavascriptMatt EnoView Answer on Stackoverflow
Solution 3 - JavascriptThomasReggiView Answer on Stackoverflow
Solution 4 - JavascriptKyleMitView Answer on Stackoverflow
Solution 5 - JavascriptkennebecView Answer on Stackoverflow
Solution 6 - JavascriptRafael Corrêa GomesView Answer on Stackoverflow
Solution 7 - JavascriptAbdurRAHMAN AyyıldızView Answer on Stackoverflow
Solution 8 - JavascriptThức TrầnView Answer on Stackoverflow