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"
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?
context['$1']is evaluated toundefinedbefore being passed into the function. You need to use a callback function to do dynamic computations based on matches.