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

后端 未结 9 2064
礼貌的吻别
礼貌的吻别 2020-11-30 01:51

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 sh

9条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-30 02:17

    In Perl, one can also write

    tr{-_}{+/}
    

    as

    my %trans = (
       '-' => '+',
       '_' => '/',
    );
    
    my $class = join '', map quotemeta, keys(%trans);
    my $re = qr/[$class]/;
    
    s/($re)/$trans{$1}/g;
    

    This latter version can surely be implemented in JS without much trouble.

    (My version lacks the duplication of Jonathan Lonowski's solution.)

提交回复
热议问题