Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Find the correct word by incrementing letters in alphabet

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading