最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - replace characters in string with regex JS - Stack Overflow

programmeradmin0浏览0评论

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
Add a ment  | 

3 Answers 3

Reset to default 4

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

发布评论

评论列表(0)

  1. 暂无评论