skip to Main Content
function dnaStrand(dna){
 const compl = dna;
 dna.includes("A") && compl.replace(/A/g, "T");
 dna.includes("T") && compl.replace(/T/g, "A")
 dna.includes("C") && compl.replace(/C/g, "G")
 dna.includes("G") && compl.replace(/G/g, "C")
 console.log(compl)
 return compl
}

I intend to form the complementary dna strand, that is, A is complementary to T and C is complemantary to G.

input >>> output
ATGC >>>> TACG

2

Answers


  1. String.replace does not modify the original string (why? Because String is immutable).

    You can try to remap the values, something like:

    console.log(dnaStrand(`ATGC`));
    
    function dnaStrand(dna){
     return [...dna].map( v => {
      switch(v) {
        case `A`: return `T`;
        case `T`: return `A`;
        case `C`: return `G`;
        default: return `C`
      }
     }).join(``);
    }
    Login or Signup to reply.
  2. Issue is you are using replace and strings are imutable in JS so the interpreteur is not modifying the string but rather raturning a new modifyed string

    also in your example you have a logical issue in your replacements: once you replace ‘A’ with ‘T’, if you immediately replace ‘T’ with ‘A’, it will revert the first replacement.

    Here is how you can achieve desired results using a map:

        function dnaStrand(dna) {
          const complements = {
            'A': 'T',
            'T': 'A',
            'C': 'G',
            'G': 'C'
          };
          
          const compl = dna.split('').map(char => complements[char]).join('');
          
          console.log(compl);
          return compl;
        }
        
        console.log(dnaStrand("ATGC"));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search