3

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?

1
  • 1
    context['$1'] is evaluated to undefined before being passed into the function. You need to use a callback function to do dynamic computations based on matches. Commented Nov 23, 2016 at 1:29

1 Answer 1

8

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

Sign up to request clarification or add additional context in comments.

1 Comment

God, I love stackoverflow — thank you! This was exactly my problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.