考慮此javascript:的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()
。
剛注意到一個錯字。將'var joe'重命名爲'var values' – Tauren 2010-05-22 05:17:17
另一個類似的問題有@ J-P替代解決方案來解答這裏的答案。它看起來相當優雅:http://stackoverflow.com/questions/3344392/dynamic-deep-selection-for-a-javascript-object/3344487#3344487 – Tauren 2010-07-28 00:28:15