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
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
Share Improve this question edited Sep 26, 2019 at 11:58 IlGala 3,4194 gold badges40 silver badges52 bronze badges asked May 26, 2017 at 17:26 MaxESMaxES 811 silver badge7 bronze badges 2- What are you trying to replace them with? – Benjamin Commet 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. – 15ee8f99-57ff-4f92-890c-b56153 Commented May 26, 2017 at 17:30
3 Answers
Reset to default 4I suggest bining 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));
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'));
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);