Hi I came acroos this challenge from jschallenger page. I write the following code and It’s working Fine unless any capital letter is passed. It seems to me ltr = "abcdefghijklmnopqrstuvwxyz" is not the right way. Could you please tell how can I improve my code?
function myf(a){
let ltr = "abcdefghijklmnopqrstuvwxyz"
let newstr =""
for(i=0; i<=a.split("").length-1; i++){
let str = ltr.indexOf(a.charAt(i))+1
let mystr = ltr.charAt(str )
newstr += mystr
}
console.log(newstr)
}
myf("bnchm") // result: coding
myf("bgddrd") // result: cheese
myf("sdrshmf")// result:testing
>Solution :
You can use charCodeAt to get the code of the letter, you can increment by one, to get the code of the next letter, and you can use fromCharCode to get the character, This will work for capital and small characters.
function myf(a){
let newstr =""
for(i=0; i<=a.split("").length-1; i++){
let str = a[i];
let code = str.charCodeAt()
// if the letter equal to z make it a
let nextCode = code === 122 ? 97 : code === 90 ? 65 : code + 1
let nextCharacter = String.fromCharCode(nextCode)
newstr += nextCharacter
}
console.log(newstr)
}
myf("bnchmf") // result: coding
myf("BNCHMF") // result: CODING
myf("bgddrd") // result: cheese
myf("sdrshmf")// result:testing
myf("zmfkd") // result: angle