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

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

    I can't vouch for 'efficient' but this uses a regex and a callback to provide the replacement character.

    function tr( text, search, replace ) {
        // Make the search string a regex.
        var regex = RegExp( '[' + search + ']', 'g' );
        var t = text.replace( regex, 
                function( chr ) {
                    // Get the position of the found character in the search string.
                    var ind = search.indexOf( chr );
                    // Get the corresponding character from the replace string.
                    var r = replace.charAt( ind );
                    return r;
                } );
        return t;
    }
    

    For long strings of search and replacement characters, it might be worth putting them in a hash and have the function return from that. ie, tr/abcd/QRST/ becomes the hash { a: Q, b: R, c: S, d: T } and the callback returns hash[ chr ].

提交回复
热议问题