Trying to get number for each character in str

时间:2018-06-04 17:29:20

标签: javascript loops for-loop

I am doing a coding and question and I can't see where I am going wrong. I am asked to print out each number for every corresponding letter.

EG. a = 1 b = 2

Also to remove any special characters and spaces.

Below is my code, greatly appreciated :)

 function alphabetPosition(str) {
   str.split('');
   var emptyArr = [];
   var letters = /^[A-Za-z]+$/;
   for(i=0; i <= str.length; i++){
    if(str[i].match(letters)){
     var num = str[i].charCodeAt(0) - 96
     emptyArr.push(num)
     var arrStr = emptyArr.toString();

     return arrStr


     }else{
      console.log('didnt match');
     }

   }
}

alphabetPosition('sunset')

so hello man should print out "19 21 14 19 5 20"

4 个答案:

答案 0 :(得分:2)

Your code has to return the value after the for loop.

 function alphabetPosition(str) {
   str = str.split('');
   var emptyArr = [];
   var letters = /^[A-Za-z]+$/;
   for(i=0; i < str.length; i++){
    if(str[i].match(letters)){
     var num = str[i].charCodeAt(0) - 96
     emptyArr.push(num)
     }else{
      console.log('didnt match');
     }
   }
   return emptyArr.toString()
}
console.log(alphabetPosition('sunset'))

Also another way to do it :

alphabetPosition=t=>t.match(/[a-z]/gi).map(i=>parseInt(i,36)-9).join(" ")
console.log(alphabetPosition('sunset'))

答案 1 :(得分:0)

Your return is too early. Move it (and the toString() call) outside the loop and your code should work.

答案 2 :(得分:0)

Don't return inside the for loop

function alphabetPosition(str) {
   str.split('');
   var res = [];
   var letters = /^[A-Za-z]+$/;

   for(i=0; i < str.length; i++){
    if(str[i].match(letters)){
     var num = str[i].charCodeAt(0) - 96
     res.push(num)

     }else{
      console.log('didnt match');
     }

   }
   return res.join(' ')
}

答案 3 :(得分:0)

You could use parseInt for the character with radix 36 and use an offset of -9 for getting the values.

function alphabetPosition(string) {
    return Array
        .from(
            string,
            c => parseInt(c, 36) - 9
        )
        .join(' ');
}

console.log(alphabetPosition('sunset'))