Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
185
rated 0 times [  186] [ 1]  / answers: 1 / hits: 32165  / 9 Years ago, mon, october 12, 2015, 12:00:00

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

More From » string

 Answers
20

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


[#64767] Thursday, October 8, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
angelicajayleneh

Total Points: 216
Total Questions: 110
Total Answers: 100

Location: Sudan
Member since Tue, Aug 3, 2021
3 Years ago
;