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

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

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

Leave a Comment