简体   繁体   中英

Is any Perl like translation in JavaScript?

Is there any inbuilt function for each string translation to another string in JavaScript?

For example

A <=> T

G <=> C 

My input string like this AAATATATTGC I want to convert all A to T T to A C to G G to C . I want to output is TTTATATAACG .

In Perl, for this kind of situation easily do it.

my $s = "AAATATATTGC";  
$s =~tr/ATGC/TACG/;

I got the result.

Like perl, is any possible way for to do it in JavaScript.?

You can use String#replace with callback.

 // An object to use as replacement var replacement = { A: 'T', T: 'A', C: 'G', G: 'C' }; // Match a single upperCase character from given characters var result = 'AAATATATTGC'.replace(/[ATCG]/g, function(_) { return replacement[_]; // Use the value of the key as replacement }); document.body.innerHTML = result; 

A slight variation using a new Map construct to avoid a hand-coded callback, which can be more reusable and composable than tying a function to a closured variable:

// replacements:
var reps= new Map([
    ['A','T'],
    ['T','A'],
    ['C','G'],
    ['G','C']
]);

var result = 'AAATATATTGC'.replace(/[ATCG]/g, reps.get.bind(reps));
// == "TTTATATAACG"

Maps are also more broadly useful as a look up table pattern because 0 , "0" , and [0] can all be distinct lookup keys...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM