Replace with group DNA

Tell us what’s happening:

I am trying here to replace G with GC, C with CG, same goes for A and T. There is some problem in my code can any one point me out in right direction

Your code so far

function pairElement(str) {

return str.replace(/(G)+|(C)+|(A)+|(T)+/,"$1C","$2F","$3T","$4A");



Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36.

Challenge: DNA Pairing

Link to the challenge:

1- replace takes only two arguments
2- for replace to substitute all instances of a character you need to use g
3- if you write G+ that means one or more, so if you have GG that becomes GGC instead of GCGC (if everything else is correct)

if you want to do it with replace maybe look in using a callback

and it is not a bad idea to look how it works overall:

1 Like

return str.replace(/(G)|(C)|(A)|(T)/g,"$1C","$2G","$3T","$4A"); remove + from groups and follwing is output


I checked and "$1C" is only working rest of the parameter does not work.

it was my first point

there are 5 in your code, the last 3 are ignored

I will try to figure out something, if i don’t get anything i will ping u

will you try the callback suggestion or something else?

Yes i am going to try callback function as a 2nd parameter in replace()

function pairElement(str) {

  function replacer(match, p1, p2, p3,p4, offset, string)   {
      return p1+"C ";
    }else if(match==="C"){
      return p2+"G "
    }else if(match==="A"){
      return p3+"T ";
    }else if(match==="T"){
      return p4+"A "

  return str.replace(/(G)|(C)|(A)|(T)/g,replacer);

// GC CG GC 

I got what i found but i don’t want to use if-else ifinside replacer(). How can i acheive the same output using another logic inside replacer func point me out in some direction

you can use an object

also, you can use only match in this case. you don’t need all the other parameters

1 Like

By object you mean

let obj = {

Something like that ??

something like that

you can use a series of nested ternary operators

you can use switch

Tell me how to do with ternary operator, i mean what we would put at the false place. I mean at the place of false should we call the function again or what. Since each Match will be true in the given testcase Condition? true : false

the ternary operator would be in place of your if/else if chain
a ternary operator is just a fancy if/else statement

You are a live saver, thank you so much