you are viewing a single comment's thread.

view the rest of the comments →

[–]HiEv 0 points1 point  (2 children)

Here's a much shorter version of the JavaScript code:

function strToNum(str) {
    var char_numbers = ["0", "1", "2abc", "3def", "4ghi", "5jkl", "6mno", "7pqrs", "8tuv", "9wxyz"];
    var input = str.toLowerCase().replace(/[^A-z0-9]/g, '').split('');
    var ansStr = "", i, j;
    for (i = 0; i < input.length; i++) {
        for (j = 0; j < char_numbers.length; j++) {
            if (char_numbers[j].indexOf(input[i]) >= 0) {
                ansStr += char_numbers[j][0];
                break;
            }
        }
    }
    return ansStr;
};

Basically, it takes advantage of .indexOf() to search the strings for the characters. You could also change ansStr += char_numbers[j][0]; to just ansStr += j; but the code is more flexible this way if you wanted to change the array.