Skip to content Skip to sidebar Skip to footer

Javascript Regex Replace Using Object Property Lookup From Match Is "undefined"

I am having the following issue while trying to perform a regex substitution: Here is my string and regex: var content = 'This is the city of {{city}}, located in the county of {{c

Solution 1:

context['$1']is undefined; there's no property named $1 on your context object.

Rather than a static replacement value, you can provide a callback function as the second argument to String.prototype.replace(pattern, callback). The callback function will be invoked for each match... receiving the matched text and any capture group values as arguments. You can do your processing based on those values and contextually return a replacement value.

var content = "This is the city of {{city}}, located in the county of {{county}} and the state of {{state}}";

var context = {
  city: "Abanda",
  county: "Chambers County",
  state: "Alabama"
};

var output = content.replace(/\{\{([a-z0-9]+)\}\}/gi, (match, key) => context[key]);

console.log(output);

Post a Comment for "Javascript Regex Replace Using Object Property Lookup From Match Is "undefined""