Alex Kom
Alex Kom

Reputation: 163

Convert letter to number in JavaScript

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.

Upvotes: 16

Views: 48428

Answers (9)

user1636522
user1636522

Reputation:

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.

Upvotes: 62

samo0ha
samo0ha

Reputation: 3788

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 }

Upvotes: 1

Anirudh Goel
Anirudh Goel

Reputation: 1

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.

Upvotes: 0

spencer robertson
spencer robertson

Reputation: 11

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

Upvotes: 1

kennebec
kennebec

Reputation: 104760

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

Erik van de Ven
Erik van de Ven

Reputation: 4975

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

Upvotes: 9

Royi Namir
Royi Namir

Reputation: 148524

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

Upvotes: 1

Amit Joki
Amit Joki

Reputation: 59232

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

Upvotes: 1

meskobalazs
meskobalazs

Reputation: 16041

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.

Upvotes: 3

Related Questions