How would I find the numerical value of a given string in JavaScript?

I did some digging on SO and discovered that a question like this has got a lot of ire from the community. So I'll just clarify for those who haven't got it yet.

Say I have a string like "Aravind". The numerical value of that string in cryptography would be:
1 18 1 22 9 14 4." This happens because, in "Aravind", the first letter "A" is the first letter in the alphabet, so the numerical value of "A" would be 1. Same with "R", the 18th letter, so numerical value of "R" is 18. This keeps on going.

So right now I'm creating a program which includes converting a given string to it's numerical value.

var latin_array = ["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 integ_array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
12 , 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26];

function parseToNumber (str) {
    var spl = str.split("");
    spl.forEach(function (x) {
        latin_array.forEach(function (y) {
            if (x == y) {
                // whatever i want goes here
            }
        })
    })
}

This is how far I've gotten, and I know anyway I made a hundred mistakes. Please forgive me, I'm just 12! So, again I want the numerical a=1, b=2, c=3, d=4 kind of value.

Thanks in advance!

Upvotes: 1

Views: 111

Answers (1)

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167172

Will something like this work?

function alphabetPosition(text) {
  var result = "";
  for (var i = 0; i < text.length; i++) {
    var code = text.toUpperCase().charCodeAt(i)
    if (code > 64 && code < 91) result += (code - 64) + " ";
  }

  return result.slice(0, result.length - 1);
}
console.log(alphabetPosition("Aravind"));

I get 1 18 1 22 9 14 4 for Aravind. I bet the original Kata is same.

Upvotes: 2

Related Questions