Replacing letters in a string using javaScript

42 Views Asked by At
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

There are 2 best solutions below

0
KooiInc On

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(``);
}

String.replace can be used this way:

const dna = `ATGC`;
console.log(`dnaStrand(dna) => ${dnaStrand(dna)}, dna still => ${dna}`);

function dnaStrand(dna){
 const complements = {A: `T`, T: `A`, C: `G`, G: `C`};
 return dna.replace(/[ACGT]/g, letter => complements[letter]);
}

0
jakub podhaisky On

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"));