Javascript Regex to convert dot notation to bracket notation

Posted by Tauren on Stack Overflow See other posts from Stack Overflow or by Tauren
Published on 2010-05-22T04:51:52Z Indexed on 2010/05/22 5:00 UTC
Read the original article Hit count: 456

Filed under:
|

Consider this javascript:

var joe = {
    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;
});

This will output the following:

Joe Smith is currently in {location.city}, {location.state}

But I want to output the following:

Joe Smith is currently in Los Angeles, California

I'm looking for a good way to convert multiple levels of dot notation found between braces in the string into multiple parameters to be used with bracket notation, like this:

values[first][second][third][etc]

Essentially, for this example, I'm trying to figure out what regex string and function I would need to end up with the equivalent of:

out = values[name] + " is currently in " + values["location"]["city"] +
    values["location"]["state"];

© Stack Overflow or respective owner

Related posts about regex

Related posts about JavaScript