How do you map-replace characters in Javascript similar to the 'tr' function in Perl?

qodeninja picture qodeninja · May 23, 2012 · Viewed 24.7k times · Source

I've been trying to figure out how to map a set of characters in a string to another set similar to the tr function in Perl.

I found this site that shows equivalent functions in JS and Perl, but sadly no tr equivalent.

the tr (transliteration) function in Perl maps characters one to one, so

     data =~ tr|\-_|+/|;

would map

     - => + and _ => /

How can this be done efficiently in JavaScript?

Answer

Jonathan Lonowski picture Jonathan Lonowski · May 23, 2012

There isn't a built-in equivalent, but you can get close to one with replace:

data = data.replace(/[\-_]/g, function (m) {
    return {
        '-': '+',
        '_': '/'
    }[m];
});