how to shift each letter in the given string N places down in the alphabet? Punctuation, spaces, and capitalization should remain intact. For example if the string is "ac" and num is 2 the output should be "ce". What's wrong with my code? It converts letter to ASCII and adds given number then converts from ASCII to letter back. The last line replaces space.
function CaesarCipher(str, num) {
str = str.toLowerCase();
var result = '';
var charcode = 0;
for (i = 0; i < str.length; i++) {
charcode = (str[i].charCodeAt()) + num;
result += (charcode).fromCharCode();
}
return result.replace(charcode.fromCharCode(), ' ');
}
I'm getting
TypeError: charcode.fromCharCode is not a function
Create an array of characters from the input string. Traverse the String array from the start (index 0) to end (n-1, where n is the length of an array). Perform the shift operation on each and every character of an array. Convert modified array of characters to string and return it.
The charCodeAt() method returns the Unicode of the character at a specified index (position) in a string. The index of the first character is 0, the second is 1, .... The index of the last character is string length - 1 (See Examples below). See also the charAt() method.
You need to pass an argument to the fromCharCode method using the String object. Try:
function CaesarCipher(str, num) {
// you can comment this line
str = str.toLowerCase();
var result = '';
var charcode = 0;
for (var i = 0; i < str.length; i++) {
charcode = (str[i].charCodeAt()) + num;
result += String.fromCharCode(charcode);
}
return result;
}
console.log(CaesarCipher('test', 2));
I had to modify the return statement, because it was introducing a bug for me
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With