Javascript Regex将点表示法转换为括号表示法

时间:2010-05-22 04:51:53

标签: javascript regex

考虑这个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()的情况下执行此操作。

3 个答案:

答案 0 :(得分:10)

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

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第5版标准的一部分:

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

答案 1 :(得分:0)

我不确定如何在Javascript中集成它,但这是一个使用正则表达式进行所需转换的Java代码片段:

    String[] tests = {
        "{name}",
        "{location.city}",
        "{location.state.zip.bleh}",
    };
    for (String test : tests) {
        System.out.println(test.replaceAll("\\{?(\\w+).?", "[$1]"));
    }

打印:

[name]
[location][city]
[location][state][zip][bleh]

基本上,它会将所有\{?(\w+).?替换为[$1]

答案 2 :(得分:0)

您可以查看comp.lang.javascript上发布的主题Error-free deep property access? - 这提供了一些实现您想要的方法。

对于正则表达式,您只需要/{.*?}/g