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?
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.
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.
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.
There isn't a built-in equivalent, but you can get close to one with replace
:
data = data.replace(/[\-_]/g, function (m) { return { '-': '+', '_': '/' }[m]; });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With