考虑这个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;
});
Run Code Online (Sandbox Code Playgroud)
这将输出以下内容:
Joe Smith is currently in {location.city}, {location.state}
Run Code Online (Sandbox Code Playgroud)
但我想输出以下内容:
Joe Smith is currently in Los Angeles, California
Run Code Online (Sandbox Code Playgroud)
我正在寻找一种很好的方法将字符串中大括号之间的多个点符号转换为多个参数,以便与括号表示法一起使用,如下所示:
values[first][second][third][etc]
Run Code Online (Sandbox Code Playgroud)
从本质上讲,对于这个例子,我试图弄清楚我需要用什么样的正则表达式字符串和函数来达到相当于:
out = values[name] + " is currently in " + values["location"]["city"] +
values["location"]["state"];
Run Code Online (Sandbox Code Playgroud)
注意:我想在不使用的情况下这样做eval().
CMS*_*CMS 11
使用辅助函数迭代访问属性:
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"
Run Code Online (Sandbox Code Playgroud)
在这里尝试上面的例子.
编辑:稍微优雅,使用该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"
Run Code Online (Sandbox Code Playgroud)
在这里尝试新的例子.