【问题标题】:Replace keys in string by value based on key–value entries in object根据对象中的键值条目将字符串中的键替换为值
【发布时间】:2012-06-27 07:29:49
【问题描述】:

我正在尝试根据其键值条目将字符串中的每个整数转换为对象中的对应值。例如,如果我有:

var arr = {
    "3": "value_three",
    "6": "value_six",
    "234": "other_value"
  };
var str = "I want value 3 here and value 234 here";

我会将输出解释为:

new_str = "I want value_three here and value other_value here"

【问题讨论】:

    标签: javascript string replace javascript-objects


    【解决方案1】:

    使用regex,另一种解决方案可能是这样的:

    const object = {
        "3": "value_three",
        "6": "value_six",
        "234": "other_value"
    };
    const str = "I want value 3 here and value 234 here. value 32";
    
    const replacedText1 = str.replace(/value \d+/g, v=>object[v.split(" ")[1]] || v);
    
    const replacedText2 = str.replace(/\d+/g, v=>object[v] || v);
    
    console.log(replacedText1);
    console.log(replacedText2);

    【讨论】:

    • 把12改成3再运行。其中只有一个有效-他想要value 3,但我们也必须照顾value 32
    【解决方案2】:

    假设您有一个像arr 这样的对象,定义了str 并声明了new_str。然后,假设我们的目标是通用解决方案,则以下工作:

    var arr = { "3": "value_three", "6": "value_six", "234": "other_value" };
    var str = "I want value 3 here and value 234 here";
    
    // Building a regex like `/3|6|234/g`
    let re = new RegExp(Object.keys(arr).join('|'), 'g');
    
    // Arrow function is approximately equivalent to
    // an anonymous function like `function(match) { return arr[match]; }`
    new_str = str.replace(re, match => arr[match]);
    
    console.log(new_str);

    顺便说一句,arr 给你的例子是Object。 (我意识到它们有时也被称为关联数组;只是指出来)。

    【讨论】:

    • 非常好,但不是完全正确的输出。你有value value_three 而不仅仅是value_three,但我喜欢它。很惊讶它不会用2value_three4替换234
    【解决方案3】:

    2021:

    请注意

    value 3
    

    也匹配

    value 32
    

    const arr = {'3':'value_three', '6':'value_six', '234':'other_value'};
    let str = 'I want value 3 here and value 234 here';
    
    Object.keys(arr).forEach(key => str = str.replaceAll(`value ${key}`,arr[key]))
    console.log(str)

    【讨论】:

      【解决方案4】:

      我最近需要用对象的key: value 条目替换字符串,其中一些键包含特殊字符,例如大括号。因此,正如其他人所建议的那样,我们可以将 String.replace 函数与 RegExp 一起使用,并将函数作为替换值传递,但是创建 RegExp 本身存在问题,因为我们需要使用 \ 转义其中的所有特殊字符.下面是转义函数和最终替换函数的例子:

      // Escape string to use it in a regular expression
      const regexpEscape = (string) => string.replace(/[.*+\-?^${}()|[\]\\]/g, '\\$&');
      
      // Replace string with `key: value` entries of the search object.
      const stringReplace = (string, search) => {
        const regexp = new RegExp(
          Object.keys(search)
            .map((item) => regexpEscape(item))
            .join('|'),
          'g'
        );
        return string.replace(regexp, (match) => search[match]);
      };
      
      const search = {
         '{{name}}': 'John',
         '{{lastname}}': 'Doe',
         '{{age}}': 24,
      };
      
      const template = 'Hey, {{name}} {{lastname}}! Your age is {{age}}.';
      
      console.log(stringReplace(template, search));

      希望它可以帮助别人!保持安全:)

      【讨论】:

        【解决方案5】:

        你也可以在这里使用减速器,我认为它看起来更干净:

        new_str = Object.keys(dynamicValues).reduce((prev, current) => {
          return prev.replace(new RegExp(current, 'g'), dynamicValues[current]);
        }, value);
        

        【讨论】:

          【解决方案6】:

          我只是在做这件事,但这应该可行。

          var new_str = str;
          
          for (var key in arr) {
              if (!arr.hasOwnProperty(key)) {
                  continue;
              }
          
              new_str = new_str.replace(key, arr[key]);
          }
          

          如果您希望替换所有出现的数字,则需要将正则表达式合并到组合中:

          var new_str = str;
          
          for (var key in arr) {
              if (!arr.hasOwnProperty(key)) {
                  continue;
              }
          
              new_str = new_str.replace(new RegExp(key, "g"), arr[key]);
          }
          

          另外,我会选择 arr 以外的其他名称,因为这意味着它是一个数组,而它显然是一个对象。此外,请确保您只对对象使用 for-in 循环,而不是数组,因为原型泄漏和其他问题。

          你也可以用 jQuery 来做这件事,但这可能有点矫枉过正:

          var new_str = str;
          
          $.each(arr, function (key, value) {
              new_str = new_str.replace(key, value);
          });
          

          【讨论】:

          • 抱歉变量名的使用试图使用一个简单的例子。我在尝试使用 replace 方法时继续收到类型错误,是否需要键入强制转换键或类似的东西?
          • 算了,我解决了。非常感谢您的帮助和及时回复。快速提问,为什么 jquery 版本过大了?
          • 因为 jQuery 中没有任何东西可以帮助解决问题。
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2020-09-27
          • 2011-01-07
          • 2021-10-24
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多