2017-05-26 152 views
0

我想用正則表達式替換字符串中的多個字符。我是交換字母A和T以及G和C.用正則表達式替換字符串中的字符JS

function replacer(string) { 

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


} 

我有正則表達式正確嗎?

thankls

+0

什麼是你想,以取代他們? –

+0

如果你的意圖是'replacer('GATTACA')' - >'「AAAAAAA」',那麼它是正確的。但我不認爲這是你的意圖。 –

回答

3

我建議結合replace回調,其第一個參數是與地圖匹配字符從字符 - >替換如下:

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

+0

所有好的答案,但這是我正在尋找的 - 謝謝。 – MaxES

1

ATGC - 看起來你是指DNA鹼基對:)

目的是交換ATGC。假設輸入字符串從不包含字符Z,使用正則表達式的一個簡單的交換函數:

注意:更改Z與您有信心的另一個字符或符號不會出現在輸入字符串中。例如$也許?

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

1

你可以做這種方式太:

function replacer(string) { 
 
    var newString = string.replace(/([ATGC])/g, m => 
 
    { 
 
    \t 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'));