user avatar
You
How to write cesar cipher function in JavaScript? It should accept string and shift number and return encoded string
ChatGPT
ChatGPT

Certainly! The Caesar cipher is a simple substitution cipher where each letter in the plaintext is shifted a certain number of places down or up the alphabet. Here's a simple JavaScript function for a Caesar cipher:

javascript
function caesarCipher(str, shift) { // Check if the shift is within the valid range (0-25) if (shift < 0 || shift > 25) { throw new Error('Shift must be between 0 and 25'); } // Convert the string to uppercase for consistency str = str.toUpperCase(); let result = ''; for (let i = 0; i < str.length; i++) { let char = str[i]; // Check if the character is a letter if (char.match(/[A-Z]/)) { // Convert the character code to a number (A=65, B=66, ..., Z=90) let code = str.charCodeAt(i); // Apply the shift and handle wrapping around the alphabet code = ((code - 65 + shift) % 26 + 26) % 26 + 65; // Convert the code back to a character and append to the result result += String.fromCharCode(code); } else { // If the character is not a letter, leave it unchanged result += char; } } return result; } // Example usage: const plaintext = 'Hello, World!'; const shiftAmount = 3; const ciphertext = caesarCipher(plaintext, shiftAmount); console.log(ciphertext); // Outputs: 'KHOOR, ZRUOG!'

This function takes a string (str) and a shift amount (shift) as input and returns the encoded string. It shifts only alphabetical characters and maintains the case. Non-alphabetical characters remain unchanged. Note that in the example, the shift amount is 3, but you can change it to any other integer.