Lucas Lucas - 9 days ago 6
Javascript Question

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 {{county}} and the state of {{state}}"
content.replace(/\{\{([a-zA-Z0-9]*)\}\}/g, '$1')



"This is the city of city, located in the county of county and the state of state"`


Here is my context object for my regex substitution:

var context = {city: "Abanda", county: "Chambers County", state: "Alabama"}
content.replace(/\{\{([a-zA-Z0-9]*)\}\}/g, context['$1'])



"This is the city of undefined, located in the county of undefined and the state of undefined"strong text


Why is my regex replace failing with
undefined
? I am following MDN's docs for regex substitution and matching here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#special-capturing-parentheses

While debugging this issue, I got the following, which highlights that there might be an issue when accessing an object's properties inside of a regex replace method:

content.replace(/\{\{([a-zA-Z0-9]*)\}\}/g, '$1')



"This is the city of city, located in the county of county and the state of state"


content.replace(/\{\{([a-zA-Z0-9]*)\}\}/g, context)



This is the city of [object Object], located in the county of [object Object] and the state of [object Object]


Can anyone explain?

Answer

Simply, 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);

Comments