Code Wars: Replace With Alphabet Position
https://www.codewars.com/kata/546f922b54af40e1e90001da/train/javascript
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
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) {
//split string into array of letters only
let sentence = text.toLowerCase().split("");
for (let i = sentence.length - 1; i >= 0; i--) {
if(sentence[i].match(/[a-z]/) === null) {
sentence.splice(i, 1);
}
}
//create an array of alphabets (97 represents lower case "a", 65 would be "A")
let alphaArr = [];
for (let i = 0; i < 26; i++) {
alphaArr.push(String.fromCharCode(97 + i));
}
//replace each letter with its index in the alphabet
return sentence.map(item => alphaArr.indexOf(item) + 1).join(" ");
}
Comments
Post a Comment