Home > Net >  Is there a way to convert certain values from an input and display others in a sequential order?
Is there a way to convert certain values from an input and display others in a sequential order?

Time:11-05

So, I am trying to create a DNA to RNA sequence converter, but it isn't really displaying when I try to get the values and change them sequentially. I.E., when you type certain letters like ATG they will convert into UAC but in that specific order. Is there a way to? I've already tried an array but it isn't working.

JS:

   var dna = document.getElementById("input1").value;
         var rna = [];
        var aminoacid;


        function replace(){
        if (dna.indexOf('a') > -1)
        {
         rna.push("u");
        } else if(dna.indexOf('t') > -1){
            rna.push("a");

        } else if(dna.indexOf('c') > -1){
            rna.push("g");

        }
        else if(dna.indexOf('g') > -1){
            rna.push("c");

        }


        }

        document.getElementById("total").innerHTML = rna;

HTML:


  <input style="top: -350px;" placeholder="Type DNA's value..." onclick="onClick();" id="input1">

  <button type="button" onclick="getInputValue();" id = "button1" style = "position: relative; z-index: 100; top: -300px; left: -200px;">Get RNA</button>

CodePudding user response:

You can use String.prototype.replace() for this.

Replace docs

For example:

let DNA = 'ATG'
DNA = DNA.replace('A', 'U');
DNA = DNA.replace('T', 'A');
DNA = DNA.replace('G', 'C');
console.log(DNA);

CodePudding user response:

This should be what you are looking for:

const input = document.querySelector('#input1').value,
      total = document.querySelector('#total');

let rna = input.replaceAll(/[atcg]/g, e =>
  e == 'a' ? 'u' :
  e == 't' ? 'a' :
  e == 'c' ? 'g' :
  e == 'g' ? 'c' :
  ' '
);

total.textContent = rna;

CodePudding user response:

You have several problems:

  • You are getting the value of the input immediately (before anyone has had a chance to enter anything.
  • You are attempting to produce the output immediately (your code that shows the result is outside of the function).
  • You are trying to directly show an array, rather than the contents of the array.
  • Because you are using else if, your value will only be checked for, at most, one value.

Is this what you are after?

var dna = document.getElementById("input1");
var rna = [];
var aminoacid;


function replace(){
  let val = dna.value;
  if (val.indexOf('a') > -1) {
    rna.push("u");
  }
  if(val.indexOf('t') > -1){
    rna.push("a");
  }
  if(val.indexOf('c') > -1){
    rna.push("g");
  }
  if(val.indexOf('g') > -1){
    rna.push("c");
  }
  document.getElementById("total").textContent = rna.join("");
}
<input placeholder="Type DNA's value..." id="input1">
<button type="button" onclick="replace();" id = "button1">Get RNA</button>
<div id="total"></div>

  • Related