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
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.