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

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

    Method:

    String.prototype.mapReplace = function(map) {
        var regex = [];
        for(var key in map)
            regex.push(key.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"));
        return this.replace(new RegExp(regex.join('|'),"g"),function(word){
            return map[word];
        });
    };
    

    A perfect example:

    var s = "I think Peak rocks!"
    s.mapReplace({"I think":"Actually","rocks":"sucks"})
    // console: "Actually Peak sucks!"
    
    0 讨论(0)
  • 2020-11-30 02:29

    This functions, which are similar how it's built in Perl.

    function s(a, b){ $_ = $_.replace(a, b); }
    function tr(a, b){ [...a].map((c, i) => s(new RegExp(c, "g"), b[i])); }
    
    $_ = "Εμπεδοκλης ο Ακραγαντινος";
    
    tr("ΑΒΓΔΕΖΗΘΙΚΛΜΝΟΠΡΣΤΥΦΧΩ", "ABGDEZITIKLMNOPRSTIFHO");
    tr("αβγδεζηθικλμνοπρστυφχω", "abgdezitiklmnoprstifho");
    s(/Ξ/g, "X"); s(/Ψ/g, "Ps");
    s(/ξ/g, "x"); s(/ψ/g, "Ps");
    s(/ς/g, "s");
    
    console.log($_);

    0 讨论(0)
  • 2020-11-30 02:30

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

    data = data.replace(/[\-_]/g, function (m) {
        return {
            '-': '+',
            '_': '/'
        }[m];
    });
    
    0 讨论(0)
提交回复
热议问题