Last updated on November 13th, 2024 at 09:35 am
This JavaScript code defines two functions, str_to_num
and num_to_str
, to convert a text string to a sequence of numbers and vice versa, with a basic encoding/decoding method
<script LANGUAGE="JavaScript">
var str_in;
var str_out = "";
var num_in;
var num_out = "";
var e = "Enter Text!";
function str_to_num(form) {
num_out = "";
if(form.input.value == "") {
alert(e);
} else {
str_in = escape(form.input.value);
for(let i = 0; i < str_in.length; i++) {
// Encode each character and separate with a space for readability
num_out += (str_in.charCodeAt(i) - 23) + " ";
}
form.output.value = num_out.trim(); // Trim the trailing space
form.input.value = "";
}
}
function num_to_str(form) {
str_out = "";
if(form.output.value == "") {
alert(e);
} else {
num_out = form.output.value.trim(); // Trim any extra spaces
let numArray = num_out.split(" "); // Split by spaces
for(let i = 0; i < numArray.length; i++) {
num_in = parseInt(numArray[i]) + 23;
str_out += String.fromCharCode(num_in); // Convert to character directly
}
form.input.value = unescape(str_out);
form.output.value = "";
}
}
</script>
Function str_to_num
- Purpose: Converts a string (
str_in
) into a sequence of numbers (num_out
). - Steps:
- If the input text field is empty, it alerts with the message
"Enter Text!"
. - Escapes the text and loops through each character, converts it to a character code, and subtracts 23 from each code, appending it to
num_out
. - Displays the resulting number sequence in the output text field and clears the input field.
- If the input text field is empty, it alerts with the message
Function num_to_str
- Purpose: Converts the sequence of numbers (
num_out
) back to the original string (str_out
). - Steps:
- If the output field is empty, it alerts with
"Enter Text!"
. - For each pair of digits in the number sequence, it converts it to an integer, adds 23 to retrieve the original character code, and then converts it back to a character.
- Displays the decoded string in the input field and clears the output field.
- If the output field is empty, it alerts with
HTML CODE
<center>
<form name=encryptform>
<table>
<tr>
<td align=center>Original String</td>
<td> </td>
<td align=center>Encrypted Code</td>
</tr>
<tr>
<td align=center><input name=input type=text size=40 value="Mistonline Encryption"/></td>
<td align=center>
<input type=button value="Decrypt" onClick="javascript:num_to_str(this.form)"/><br />
<input type=button value="Encrypt" onClick="javascript:str_to_num(this.form)"/>
</td>
<td align=center><input name=output type=text size=40/></td>
</tr>
</table>
</form>
</center>