Ox.formatString: support '{a.b.c}' access to nested object properties

This commit is contained in:
rlx 2013-03-05 06:06:58 +00:00
parent 42760324f3
commit f34d70fd4c

View file

@ -682,10 +682,22 @@ Ox.formatString <f> Basic string formatting
'foobar'
> Ox.formatString('{a}{b}', {a: 'foo', b: 'bar'})
'foobar'
> Ox.formatString('{a.x}{a.y}', {a: {x: 'foo', y: 'bar'}})
'foobar'
> Ox.formatString('{a\\.b}', {'a.b': 'foobar'})
'foobar'
@*/
Ox.formatString = function(string, collection) {
return string.replace(/\{([^}]+)\}/g, function(string, match) {
return collection[match];
// make sure to not split at escaped dots ('\.')
var keys = match.replace(/\\\./g, '\n').split('.').map(function(key) {
return key.replace(/\n/g, '.')
}),
value = collection;
while (keys.length) {
value = value[keys.shift()];
}
return value;
});
};