Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
DNA to RNA conversion using JavaScript
Deoxyribonucleic acid (DNA) is the primary information storage molecule in biological systems. It is composed of four nucleic acid bases: Guanine ('G'), Cytosine ('C'), Adenine ('A'), and Thymine ('T').
Ribonucleic acid (RNA) is the primary messenger molecule in cells. RNA differs slightly from DNA in its chemical structure and contains no Thymine. In RNA, Thymine is replaced by another nucleic acid called Uracil ('U').
Problem
We need to write a JavaScript function that translates a given DNA string into RNA by replacing all 'T' nucleotides with 'U' nucleotides.
Using For Loop
The most straightforward approach is to iterate through each character and replace 'T' with 'U':
const DNA = 'GCAT';
const DNAtoRNA = (dnaString) => {
let rna = '';
for(let i = 0; i < dnaString.length; i++){
if(dnaString[i] === 'T'){
rna += 'U';
} else {
rna += dnaString[i];
}
}
return rna;
};
console.log(DNAtoRNA(DNA));
console.log(DNAtoRNA('ATCGATCG'));
GCAU AUCGAUCG
Using String Replace Method
A more concise approach uses the built-in replace() method with a global flag:
const DNAtoRNA = (dnaString) => {
return dnaString.replace(/T/g, 'U');
};
console.log(DNAtoRNA('GCAT'));
console.log(DNAtoRNA('TTAACCGG'));
console.log(DNAtoRNA('AAATTTCCCGGG'));
GCAU UUAACCGG AAAUUUCCCGGG
Using Split and Join
Another approach splits the string on 'T' and joins with 'U':
const DNAtoRNA = (dnaString) => {
return dnaString.split('T').join('U');
};
console.log(DNAtoRNA('ATGC'));
console.log(DNAtoRNA('TATATA'));
AUGC UAUAUA
Comparison
| Method | Readability | Performance | Best For |
|---|---|---|---|
| For Loop | Good | Fast | Learning/Understanding |
| String Replace | Excellent | Fast | Production Code |
| Split/Join | Good | Slower | Simple Cases |
Complete Example with Validation
const DNAtoRNA = (dnaString) => {
// Validate input
if (typeof dnaString !== 'string') {
throw new Error('Input must be a string');
}
// Check for valid DNA bases
const validBases = /^[ATCG]*$/;
if (!validBases.test(dnaString)) {
throw new Error('Invalid DNA sequence. Only A, T, C, G allowed');
}
return dnaString.replace(/T/g, 'U');
};
// Test cases
console.log(DNAtoRNA('ATCG'));
console.log(DNAtoRNA(''));
console.log(DNAtoRNA('AAATTTCCCGGG'));
try {
console.log(DNAtoRNA('ATCGX')); // Invalid base
} catch (error) {
console.log('Error:', error.message);
}
AUCG AAAUUUCCCGGG Error: Invalid DNA sequence. Only A, T, C, G allowed
Conclusion
DNA to RNA conversion in JavaScript is straightforward using string replacement methods. The replace(/T/g, 'U') approach is most efficient and readable for production code.
