【问题标题】:replace characters in a string using an associative array mapping使用关联数组映射替换字符串中的字符
【发布时间】:2015-03-10 11:17:37
【问题描述】:

我有一个这样的关联数组/对象:

mymap = {'e':'f', 'l':'g'};

我想用上面的代码作为一个简单的密码替换字符串中的所有匹配字符,但只替换现有字符。例如,

input = "hello world";
output = input.map(mymap); //how can I do this?
//output is "hfggo worgd"

平衡性能(对于大输入)和代码大小很重要。


我的应用程序正在使用 this map 将 unicode 字符替换为乳胶字符串,但我很乐意坚持更一般的问题。

【问题讨论】:

    标签: javascript replace associative-array


    【解决方案1】:

    以下作品:

    mymap = {'e':'f', 'l':'g'};
    
    var replacechars = function(c){
        return mymap[c] || c;
    };
    
    input = "hello world";
    output = input.split('').map(replacechars).join('');
    

    虽然必须拆分然后加入输入看起来很迂回,特别是如果这应用于文本墙。

    【讨论】:

      【解决方案2】:

      另一种方法是遍历对象属性并为每个替换使用正则表达式:

      var input = 'hello world';
      var output = '';
      
      for (var prop in mymap) {
          if (mymap.hasOwnProperty(prop)) {
              var re = new RegExp(prop, 'g');
              output = input.replace(re, mymap[prop]);
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-04-26
        • 2021-09-23
        • 1970-01-01
        • 1970-01-01
        • 2014-03-21
        • 2021-11-15
        • 2018-09-11
        • 1970-01-01
        相关资源
        最近更新 更多