Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
197
rated 0 times [  199] [ 2]  / answers: 1 / hits: 34724  / 12 Years ago, wed, may 23, 2012, 12:00:00

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?


More From » perl

 Answers
49

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



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

[#85391] Tuesday, May 22, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
isham

Total Points: 69
Total Questions: 86
Total Answers: 86

Location: Anguilla
Member since Sun, Jan 29, 2023
1 Year ago
;