题目
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 ita being 1, b being 2, etc.
As an example:
alphabet_position("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.
将传入的字符串,转化为每个字母对应的顺序组成数字字符串。
我的答案
function alphabetPosition(text) {
let arr =['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'];
let index = []
for(let i=0;i<text.length;i++){
for(let j=0;j<arr.length;j++){
if(/^[A-Za-z]*$/.test(text[i]) && text[i].toLowerCase() === arr[j]){
index.push(j+1)
}
}
}
return index.join(' ');
}
票数最高的答案:
ex: alphabetPosition("The twelve o' clock.")
function alphabetPosition(text) {
return text
.toUpperCase() // THE TWELVE O' CLOCK.
.replace(/[^A-Z]/g, '') // THETWELVEOCLOCK
.split('') // ["T", "H", "E", "T", "W", "E", "L", "V", "E", "O", "C", "L", "O", "C", "K"]
.map( (c) => c.charCodeAt() - 64) // [20, 8, 5, 20, 23, 5, 12, 22, 5, 15, 3, 12, 15, 3, 11]
.join(' '); // 20 8 5 20 23 5 12 22 5 15 3 12 15 3 11
}
思考:
1、我用了一个最笨的方式去确定所有字母对应的数字
2、'a'.charCodeAt() =》 97: 打印字母"a"的十进制表示形式
'A'.charCodeAt() =》 65: 打印字母"A"的十进制表示形式