Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to replace a string by array

const  num_rep = ["A;1", "B;2", "C;3"]; 
const string = 'AABAC.';

How to make every "A" become "1", "B" become "2" and "C" become "3"?

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

here is the simple almost one-liner to replace symbols with another:

const num_rep = ["A;1", "B;2", "C;3"]; 
const string = 'AABAC.';

let num_rep_map = num_rep.map(a => a.split(';')).reduce((p, c) => {p[c[0]]=c[1]; return p;}, {});
console.log(string.split('').map(a => num_rep_map[a]??a).join(''));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading