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

后端 未结 9 2051
礼貌的吻别
礼貌的吻别 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:09

    Here is a function that receives text orig dest and replaces in text each character for the one in the corresponding position in dest.

    Is is not good enough for cases where more than one character must be replaced by only one or vice-versa. It is not good enough for removing accents from Portuguese texts, which is my use case.

    function tr(text, orig, dest) {
        console.assert(orig.length == dest.length);
        const a = orig.split('').map(i=> new RegExp(i, 'g'));
        const b = dest.split('');
        return a.reduce((prev, curr, idx) => prev.replace(a[idx], b[idx]), text );
    }
    

    How to use it:

    var port  = "ÀÂÃÁÉÊÍÓÔÕÜÚÇáàãâêéíóõôúüç";
    var ascii = "AAAAEEIOOOUUCaaaaeeiooouuc";
    console.log(tr("não têm ações em seqüência", port, ascii)) ;
    

提交回复
热议问题