Decode GTCA-encoded text
This fiddle is a quick example of decoding GTCA-encoded text, linked to the YA novel This Mortal Coil
by Emily Suvada
HTML
<h3>
Type or paste text below to convert it to/from GTCA encoding
</h3>
<textarea id="input"></textarea>
<p>
<button type="button" id="encodeText">ENCODE your text into GTCA</button><br>
<button type="button" id="decodeText">DECODE your text from GTCA</button><br>
</p>
<textarea id="output"></textarea>
CSS
textarea {
display: block;
margin-left: auto;
margin-right: auto;
padding: 5px;
width: 300px;
height: 150px;
border: 3px solid #cccccc;
background: #f9f9f9;
font-family: Tahoma, sans-serif;
}
h3,
p {
text-align: center;
font-family: 'Reem Kufi', Helvetica, Arial, Lucida, sans-serif;
}
button {
background-color: #89add1; /* Green */
border: none;
color: white;
padding: 15px 32px;
margin: 8px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
}
JavaScript
// This code uses "JQuery" - a powerful javascript library that allows you to update HTML elements easily and dynamically.
//----------------------------------------------------------------
// Please note - this function doesn't do enough error-checking to
// run properly for all types of inputs. What error checks can you
// think of that it's not running?
//----------------------------------------------------------------
$(document).ready(function() {
$('#decodeText').click(function() {
// Grab the input text
var inputText = $('#input').val();
// Initialize the output to an empty string.
var outputText = "";
// Check to see if any characters other than G,T,C and A exist.
if (!/^[ATCGgtca]+$/.test(inputText)) {
outputText = "Your text can only contain G,T,C, and A! ";
}
// Check to see if the input is composed of octets
if (inputText.length % 8 !== 0) {
outputText += "This text doesn't seem to be the right length!";
}
// If there are no errors so far, convert the text.
if (outputText == "") {
// Replace all letters with the appropriate binary digits.
// Note that I'm ignoring case here, so A = a, and G = g, etc.
// Map "A" and "T" to 0:
inputText = inputText.replace(/[ATat]/g, "0");
// Map "C" and "G" to 1:
inputText = inputText.replace(/[GCgc]/g, "1");
// Split the text into an array with multiple elements.
// Each element will contain an 8-digit binary number.
var s = inputText.match(/.{1,8}/g);
// Loop through each 8-digit string and convert to a number,
// then to text, adding each letter to the output as we go
for (i = 0; i < s.length; i++) {
// Grab the current element.
var currentString = s[i];
// Convert it to a number using parseInt.
// Tell the function it's a number in base "2".
currentString = parseInt(currentString, 2);
// Convert the number to a letter...