Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Regex to convert dot notation to bracket notation

Consider this 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;
});

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"];

NOTE: I'd like to do this without using eval().

like image 752
Tauren Avatar asked May 22 '10 04:05

Tauren


1 Answers

Using a helper function to iteratively access the properties:

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"

Try the above example here.

Edit: Something slightly elegant, using the Array.prototype.reduce method, part of the new ECMAScript 5th Edition Standard:

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"

Try the new example here.

like image 67
Christian C. Salvadó Avatar answered Oct 31 '22 03:10

Christian C. Salvadó