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

十年热恋 提交于 2019-11-29 17:58:13

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!