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?
In Perl, one can also write
as
This latter version can surely be implemented in JS without much trouble.
(My version lacks the duplication of Jonathan Lonowski's solution.)
There isn't a built-in equivalent, but you can get close to one with
replace
:This will map all
a
s tob
and ally
toz
EDIT:
Apparently you can't do that with strings. Here's an alternative:
This functions, which are similar how it's built in Perl.
I can't vouch for 'efficient' but this uses a regex and a callback to provide the replacement character.
For long strings of search and replacement characters, it might be worth putting them in a hash and have the function return from that. ie, tr/abcd/QRST/ becomes the hash { a: Q, b: R, c: S, d: T } and the callback returns hash[ chr ].
Method:
A perfect example: