2

I want to replace multiple characters in a string using regex. I am trying to swap letters A and T as well as G and C.

function replacer(string) {
    return "String " + string + " is " + string.replace(/A|T|G|C/g, "A","T","G","C");
}

do I have the regex expression correct?

thanks

2
  • What are you trying to replace them with? Commented May 26, 2017 at 17:28
  • If your intent was replacer('GATTACA') -> "AAAAAAA", then it's correct. But I don't think that's your intent. Commented May 26, 2017 at 17:30

3 Answers 3

4

I suggest combining the replace callback whose first argument is the matching character with a map from character -> replacement as follows:

// Swap A-T and G-C:
function replacer(string) {
  const replacements = {'A': 'T', 'T': 'A', 'G': 'C', 'C': 'G'};
  return string.replace(/A|T|G|C/g, char => replacements[char]);
}

// Example:
let string = 'ATGCCTCG';
console.log('String ' + string + ' is ' + replacer(string));

Sign up to request clarification or add additional context in comments.

1 Comment

All good answers, but this was the one I was looking for - thanks.
2

You could do it this way too:

function replacer(string) {
    var newString = string.replace(/([ATGC])/g, m =>
    {
    	switch (m) {
          case 'A': return 'T';
          case 'T': return 'A';
          case 'G': return 'C';
          case 'C': return 'G';
      }
    });
    return "String " + string + " is " + newString;
}

console.log(replacer('GATTACAhurhur'));

Comments

1

A, T, G, C - Looks like you are referring to DNA base pairs :)

Aim is to swap A with T and G with C. Assuming the input string never contains the character Z, a simple swap function using regex:

Note: Change Z with another character or symbol that you are confident will not appear in the input string. Example $ maybe?

var input = "AAATTGGCCTAGC"
input = input.replace(/A/g,"Z").replace(/T/g,"A").replace(/Z/g,"T");
input = input.replace(/G/g,"Z").replace(/C/g,"G").replace(/Z/g,"C");
console.log(input);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.