How do you handle the shift on a Caesar cipher in Javascript?

前端 未结 1 866
一整个雨季
一整个雨季 2020-12-22 12:55

I\'m trying to create a caesar cipher in Javascript and having trouble figuring out how to do the shift. It may be that my approach is complicating it, but I\'m trying to un

相关标签:
1条回答
  • 2020-12-22 13:16

    Just have the numbers in simple array, but in order.
    var alpha = ['a', 'b', 'c', ... 'z']
    Get its number value as var value = alpha.indexOf(the_number);
    Then add the cipher key and prevent from going over your amount by using %.
    var newNumValue = (value + key) % 26; I guess that's it. It covers the question. Apart from that - your approach was good, yes.
    Different approach
    Also - if your text might contain some special symbols, i would suggest taking the initial value from ASCII table. It will cover all the symbols plus differ lowercase and uppercase letters. And you don't need to store that array.
    var value = yourChar.charCodeAt(0);
    To get symbol back from the ascii code, go var symbol = value.fromCharCode();
    Hope this helps.

    0 讨论(0)
提交回复
热议问题