Pages

Saturday, June 26, 2010

Javascript: Letters to Numbers

Letters to Numbers
Numerology involves converting text into numbers and then applying some sort of meaning to the numbers produced.

Whether you believe in numerology or not, being able to convert letters into numbers can have all sorts of applications (for example using the numbers produced to look up replacement letters from an array would be a simple way of producing a transposition cypher).

Converting letters into numbers on a computer is extremely easy because the computer stores the letters as numbers in the first place and so all we need to do is to access those number representations directly. In JavaScript this is done using the charCodeAt method that is defined for all string objects.

Let's make this simpler for ourselves by assuming that all of the content we are going to process are actually letters and omit the validation step that will reject any content that isn't alphabetic. We'll treat upper and lowecase letters identically and return an array of numbers where A=0 and Z=25 that are suitable for doing an array lookup to convert the letters into anything at all.

Here's our str2num function.

function str2num(mystr) {
mystr = mystr.toUpperCase();
var conv = [];
var l = mystr.length;
for (var i=0; i conv[i] = mystr.charCodeAt(i)-65;
}
return conv;
}The first line in our function converts all the letters to uppercase. The second line defines an array to hold the numbers we extract for each letter and the third line saves the length of our string to a variable to save our having to check the length each time around the loop.

The for loop simply calls the charCodeAt method separately for each letter in our string and then since A returns a value of 65 we simply subtract 65 from the result to give the numbers between 0 and 25 that we want. The function then simply returns the array of numbers.

Finally let's look at a working example where my name 'Stephen' gets converted into an array of numbers.(Click on my name to pop up an alert with the results).

No comments:

Post a Comment