JSFiddle - React, Tailwind, and code Playground
by digthedoug
JavaScript
var caesarShift = function (str, amount) {
// Wrap the amount
if (amount < 0) {
return caesarShift(str, amount + 26);
}
// Make an output variable
var output = "";
// Go through each character
for (var i = 0; i < str.length; i++) {
// Get the character we'll be appending
var c = str[i];
// If it's a letter...
if (c.match(/[a-z]/i)) {
// Get its code
var code = str.charCodeAt(i);
// Uppercase letters
if (code >= 65 && code <= 90) {
c = String.fromCharCode(((code - 65 + amount) % 26) + 65);
}
// Lowercase letters
else if (code >= 97 && code <= 122) {
c = String.fromCharCode(((code - 97 + amount) % 26) + 97);
}
}
// Append
output += c;
}
// All done!
return output;
};
console.log(caesarShift("Dear Chris,", 6))
console.log(caesarShift("I hope these shoes fit you well. I know how much you wanted a pair.",7))
console.log(caesarShift("I hope this puzzle didn't give you too much trouble. It should be easy enough for you to figure out.",8))
console.log(caesarShift("I hope you have a good holiday!",9))
console.log(caesarShift("P.S. Look under the paper.",10))