Reputation: 24375
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?
Upvotes: 86
Views: 191091
Reputation: 59355
This is short and supports uppercase and lowercase.
const alphaVal = (s) => s.toLowerCase().charCodeAt(0) - 97 + 1
console.log(alphaVal("a")); // output: 1
console.log(alphaVal("b")); // output: 2
console.log(alphaVal("c")); // output: 3
Upvotes: 21
Reputation: 29899
If you want to be able to handle Excel like letters past 26 like AA
then you can use the following function adapted from Count with A, B, C, D instead of 0, 1, 2, 3, ... with JavaScript:
function convertLetterToNumber(str) {
const start = 96 // "a".charCodeAt(0) - 1
const len = str.length;
const out = [...str.toLowerCase()].reduce((out, char, pos) => {
const val = char.charCodeAt(0) - start
const pow = Math.pow(26, len - pos - 1);
return out + val * pow
}, 0)
return out;
}
const testCases = ["A","B","C","Z","AA","AB","BY"];
const converted = testCases.map(convertLetterToNumber);
console.log(converted); // [1,2,3,26,27,28,77]
function convertLetterToNumber(str) {
const start = 96 // "a".charCodeAt(0) - 1
const len = str.length;
const out = [...str.toLowerCase()].reduce((out, char, pos) => {
const val = char.charCodeAt(0) - start
const pow = Math.pow(26, len - pos - 1);
return out + val * pow
}, 0)
return out;
}
const testCases = ["A","B","C","Z","AA","AB","BY"];
const converted = testCases.map(convertLetterToNumber);
console.log(converted); // [1,2,3,26,27,28,77]
Upvotes: 13
Reputation: 9
function convertLetterToNumber(str) {
if ((typeof str === "string" || str instanceof String) && /^[a-zA-Z]+$/.test(str)) {
str = str.toUpperCase();
let out = 0,
len = str.length;
for (pos = 0; pos < len; pos++) {
out += (str.charCodeAt(pos) - 64) * Math.pow(26, len - pos - 1);
}
return out;
} else {
return undefined;
}
}
let speling = prompt("Please enter your value", "ZZ");
let result=convertLetterToNumber(speling);
alert(result)
Upvotes: -1
Reputation: 137
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
Upvotes: -1
Reputation: 37
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/
Upvotes: 0
Reputation: 1907
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
Upvotes: 6
Reputation: 224905
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)
Upvotes: 160
Reputation: 104760
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
*/
Upvotes: 5
Reputation: 697
Sorry, I thought it was to go the other way.
Try this instead:
var str = "A";
var n = str.charCodeAt(0) - 65;
Upvotes: 18