Replace With Alphabet Position
题目
Welcome.
In this kata you are required to, given a string, replace every letter with its position in the alphabet.
If anything in the text isn’t a letter, ignore it and don’t return it.
“a” = 1, “b” = 2, etc.
Example
alphabetPosition(“The sunset sets at twelve o’ clock.”)
Should return “20 8 5 19 21 14 19 5 20 19 5 20 19 1 20 20 23 5 12 22 5 15 3 12 15 3 11” (as a string)
思路
过滤非字母,全部转换为小写字母之后,将字母转换为ASCII码,减去96就是字母在字母表中的位置。
然后用循环组成最后的字符串。
- .toLowerCase() 字符串转换为小写字母
- .trim() 去除字符串首尾空格
- .charCodeAt() 字符串转换为ASCII码
- [^a-zA-Z] 非字母的正则式
答案
1 | function alphabetPosition(text) { |

