如何在Javascript中映射替换字符,类似于Perl中的'tr'函数? [英] How do you map-replace characters in Javascript similar to the 'tr' function in Perl?

查看:187
本文介绍了如何在Javascript中映射替换字符,类似于Perl中的'tr'函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在试图找出如何将一个字符串中的一组字符映射到另一个类似于Perl中的 tr 函数的集合。

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.

我发现此网站显示的是等效的函数在JS和Perl ,但可悲的是没有tr等效。

I found this site that shows equivalent functions in JS and Perl, but sadly no tr equivalent.

Perl中的 tr (音译)函数将字符一一映射,因此

the tr (transliteration) function in Perl maps characters one to one, so

     data =~ tr|\-_|+/|;

会映射

     - => + and _ => /

如何在JavaScript中高效地完成?

How can this be done efficiently in JavaScript?

推荐答案

没有内置的等价物,但您可以使用 替换

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

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

这篇关于如何在Javascript中映射替换字符,类似于Perl中的'tr'函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆