Here is an example of a Caesar Cipher implementation in JavaScript:
function CaesarCipher(str, shift) {
var result = "";
for (var i = 0; i < str.length; i++) {
var char = str[i];
var charCode = str.charCodeAt(i);
if (charCode >= 65 && charCode <= 90) {
result += String.fromCharCode((charCode - 65 + shift) % 26 + 65);
} else if (charCode >= 97 && charCode <= 122) {
result += String.fromCharCode((charCode - 97 + shift) % 26 + 97);
} else {
result += char;
}
}
return result;
}
This function takes two parameters: a string and a shift value. The string is the text that you want to encrypt, and the shift value is the number of positions that each letter should be shifted by. The function uses a for loop to iterate through each character in the string, and then uses the charCodeAt() method to get the Unicode value of the character. Depending on whether the character is uppercase or lowercase, the function uses the modulus operator to shift the character’s position by the shift value.
You can use this function to encrypt a string like this:
var encrypted = CaesarCipher("HELLO WORLD", 3);
console.log(encrypted);
This will output “KHOOR ZRUOG”.
You can also create another function like this to decrypt the message
function DecryptCaesarCipher(str, shift) {
return CaesarCipher(str, 26 - shift);
}
You can use this function to decrypt a string like this:
var decrypted = DecryptCaesarCipher("KHOOR ZRUOG", 3);
console.log(decrypted);
This will output “HELLO WORLD”
Also Read:
- How To Get The Last Character Of A String In JavaScript
- Remove The Last Character Of A String In JavaScript
- How To Validate An Email Address In JavaScript
- How To Check If An Input Field Is Empty In JavaScript
- Check If An Input Field Is A Number In JavaScript
- Confirm Password Validation In JavaScript
- How To Print A PDF File Using JavaScript
- Calculate The Number Of Days Between Two Dates In JavaScript
- How To Compare Two Dates In JavaScript
- Calculate Age With Birth Date YYYYMMDD In JavaScript
- How To Append or Add Text To A DIV Using JavaScript
- How To Get The Text Of HTML Element In JavaScript
- How To Change The Text Inside A DIV Element In JavaScript
- Show/Hide Multiple DIVs In JavaScript
- Show A DIV After X Seconds In JavaScript
- Display A JavaScript Variable In An HTML Page
- How To Generate A Random Number In JavaScript
- Bubble Sort In JavaScript
- Insertion Sort In JavaScript
- Selection Sort In JavaScript
- How To Remove A Specific Item From An Array In JavaScript
- Merge Sort In JavaScript
- Round To 2 Decimal Places In JavaScript
- SetInterval() and setTimeout() Methods In JavaScript
- Generate A Unique ID In JavaScript
- Caesar Cipher In JavaScript
- How To Reverse A String In JavaScript
- How To Loop Through A Plain JavaScript Object
- How To Open A URL In A New Tab Using JavaScript?