Home >Web Front-end >JS Tutorial >How to Build a Cipher Machine with JavaScript
This tutorial shows you how to build a Caesar cipher machine using JavaScript. The Caesar cipher shifts each letter in a message a certain number of places.
We'll create an HTML page with a form to input the message and shift value, and a div to display the encrypted result.
The JavaScript code includes:
encrypt
function applying the Caesar cipher, handling non-alphabet characters and case sensitivity.Here's an example of the finished code. Experiment with creating secret messages!
First, create caesar.html
:
<code class="language-html"><!DOCTYPE html> <meta charset="utf-8"> <title>Caesar Cipher</title> <h1>Caesar Cipher</h1> <form> <label>Plaintext:</label> <textarea name="plaintext">Top Secret</textarea><br> <label>Shift:</label> <input type="number" name="shift" value="5" min="1" max="26"> <input type="submit" value="encrypt"> </form> <h2>Output</h2> <div id="output"></div> </code>
This HTML creates a simple form. The shift input defaults to 5, but you can adjust it.
Next, create main.js
in the same folder:
<code class="language-javascript">const alphabet = [ 'A','B','C','D','E','F', 'G','H','I','J','K','L', 'M','N','O','P','Q','R', 'S','T','U','V','W','X', 'Y','Z' ]; const form = document.forms[0]; const output = document.getElementById('output'); form.addEventListener ('submit',event => { event.preventDefault(); output.innerHTML = [...form.plaintext.value].map(char => encrypt(char)).join(''); }); function encrypt(char) { const shift = Number(form.shift.value); if (alphabet.includes(char.toUpperCase())) { const position = alphabet.indexOf(char.toUpperCase()); const newPosition = (position + shift)%26; return alphabet[newPosition]; } else { return char; } }</code>
This JavaScript code defines the alphabet, gets form elements, adds an event listener to handle form submission, and includes the encrypt
function which performs the Caesar cipher. The encrypt
function handles uppercase letters; lowercase letters are handled implicitly by the includes
and indexOf
methods.
This completes the Caesar cipher machine. Remember that this is a simple cipher and not suitable for secure communication.
Frequently Asked Questions (FAQs) (Summarized for brevity)
StringBuilder
for faster string manipulation.The above is the detailed content of How to Build a Cipher Machine with JavaScript. For more information, please follow other related articles on the PHP Chinese website!