考虑这个JavaScript:

var values = {
    name: "Joe Smith",
    location: {
        city: "Los Angeles",
        state: "California"
    }
}

var string = "{name} is currently in {location.city}, {location.state}";

var out = string.replace(/{([\w\.]+)}/g, function(wholematch,firstmatch) {
    return typeof values[firstmatch] !== 'undefined' ?
        values[firstmatch] : wholematch;
});

这将输出以下内容:
Joe Smith is currently in {location.city}, {location.state}

但我想输出以下内容:
Joe Smith is currently in Los Angeles, California

我正在寻找一种将字符串中的花括号之间找到的多个点表示法转换为多个要与括号表示法一起使用的参数的好方法,如下所示:
values[first][second][third][etc]

本质上,对于此示例,我试图找出最终需要得到的正则表达式字符串和函数:
out = values[name] + " is currently in " + values["location"]["city"] +
    values["location"]["state"];

注意:我想在不使用eval()的情况下执行此操作。

最佳答案

使用帮助函数来迭代访问属性:

function getNestedValue(obj, prop) {
  var value, props = prop.split('.'); // split property names

  for (var i = 0; i < props.length; i++) {
    if (typeof obj != "undefined") {
      obj = obj[props[i]]; // go next level
    }
  }
  return obj;
}

var string = "{name} is currently in {location.city}, {location.state}";

var out = string.replace(/{([^}]+)}/g, function(wholematch,firstmatch) {
  var value = getNestedValue(joe, firstmatch);
  return typeof value !== 'undefined' ? value : wholematch;
});
// "Joe Smith is currently in Los Angeles, California"

尝试上面的示例here

编辑:使用 Array.prototype.reduce 方法,稍微有些优雅,这是新ECMAScript 5th Edition Standard的一部分:
function replace(str, obj) {
  return str.replace(/{([^}]+)}/g, function(wholematch,firstmatch) {
    var value = firstmatch.split('.').reduce(function (a, b) {
      return a[b];
    }, obj);
    return typeof value !== 'undefined' ? value : wholematch;
  });
}

replace("{name} is currently in {location.city}, {location.state}", values);
// "Joe Smith is currently in Los Angeles, California"

尝试新的示例here

关于Javascript正则表达式将点表示法转换为括号表示法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/2886995/

10-10 23:53