Create a Caesar Cipher that will be able to encrypt just the letters of a sentence (given in input by the user). Special characters, spaces, and numbers will remain the same.
Input | Processing | Output |
---|---|---|
Regular sentence typed by the user |
|
Display the encrypted sentence |
function crypt() {
var myText = document.getElementById("myText").value; //myText is the textbox where the user insert the string to encrypt
var cryptedText = "";
for(var i = 0; i < myText.length; i++) //for cycle that runs the string array until its last position, obtained with its length
{
var charCode = myText.charCodeAt(i);
if((charCode >= 65 && charCode <= 90) || (charCode >= 97 && charCode <= 122)) //Check if the char is a letter or something else
cryptedText = cryptedText + String.fromCharCode(charCode+3); //If it's a letter, add 3 to its code and append it to cryptedText
else
cryptedText = cryptedText + String.fromCharCode(charCode); //If not, leave the code how it is and append it to cryptedText
}
document.getElementById("cryptedTextBox").innerHTML = cryptedText; //This is where the encripted text will show up
}
In order for the Caesar Cipher to work properly we need to acquire a sentence from a user. This will be done with a simple textbox. The request is that only letters will be encrypted, leaving special characters, numbers, and spaces alone.
It is noticeable from the code on the left, that once the string containing the original sentence is acquired, we will create a for loop, that will allow the program to "scan" every position of the array (string).
Every time a position is scanned, the character code of each letter is obtained with a function. This has been implemented in order to encrypt just letters and nothing else. In fact, it is possible to compare the character code obtained with the ones present in a ASCII table.
If this value falls in between the range declared, it means it is either a lowercase or uppercase letter. Therefore, it needs to be encrypted (simply adding a value to the character code). This, as a result has the previous letter "a" (ASCII code: 97) now a "d" (ASCII code: 100), etc...
If the character code does not fall in between the range declared, it means it's either a space, special character, or number, and doesn't need to be encrypted.
The code obtained from this process is now casted into a string and appended to a variable that will be our final encrypted sentence. This sentence will be displayed once the user hits the button that triggers the function.