Convert letter to number in JavaScript

39,427

Solution 1

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

Solution 2

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.

Solution 3

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

Solution 4

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

Solution 5

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

Share:
39,427
Alex Kom
Author by

Alex Kom

Updated on December 27, 2021

Comments

  • Alex Kom
    Alex Kom over 2 years

    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.

  • NewToJS
    NewToJS over 9 years
    You would need to +1 to the letterPosition as the first array will be 0 so "a"=0, not "a"=1.
  • David Jacquel
    David Jacquel over 9 years
    As array index starts at 0, it will give 0 for a. var letterPosition = alphabet.indexOf(letter)+1; is better.
  • Alex Kom
    Alex Kom over 9 years
    @ErikVandeVen is there a way to add the letters together using your method? e.g. aaa=3, az=27 etc.
  • Erik van de Ven
    Erik van de Ven over 9 years
    Probably, but why should "ab" be 27?
  • Alex Kom
    Alex Kom over 9 years
    I meant az sorry for the confusion.
  • Erik van de Ven
    Erik van de Ven over 9 years
    no problem ;). I will change my answer a bit, just a moment.
  • Alex Kom
    Alex Kom over 9 years
    @ErikVandeVen Thank you for your help.
  • Kick Buttowski
    Kick Buttowski almost 4 years
    but some posts used 97? very confusing :/
  • Admin
    Admin almost 4 years
    Using parseInt you don't have to deal with capital letters stackoverflow.com/a/30697101/1636522 :-)
  • Anuj Srivastava
    Anuj Srivastava over 3 years
    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. :)