Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 678
qodeninja Avatar asked May 23 '12 19:05

qodeninja


People also ask

How do I map a character in JavaScript?

Suppose we have the number 12145. We are required to write a function that maps the digits of the number to English alphabets according to the following norms. The alphabets are to be mapped according to the 1 based index, like 'a' for 1 and 'b' for 2 'c' for 3 and so on.

How do you replace letters in JavaScript?

Answer: Use the JavaScript replace() method You can use the JavaScript replace() method to replace the occurrence of any character in a string. However, the replace() will only replace the first occurrence of the specified character. To replace all the occurrence you can use the global ( g ) modifier.

How does replace method work in JavaScript?

The replace() method searches a string for a value or a regular expression. The replace() method returns a new string with the value(s) replaced. The replace() method does not change the original string.


1 Answers

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

data = data.replace(/[\-_]/g, function (m) {     return {         '-': '+',         '_': '/'     }[m]; }); 
like image 166
Jonathan Lonowski Avatar answered Sep 20 '22 05:09

Jonathan Lonowski