Search code examples
javascriptarraysreplacestr-replace

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

  • 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(''));