Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialY. Kravets
10,350 PointsQuestion about the implementation
I keep getting 'Your implementation is off'. In this code I am simply specifying a regex to replace everything between (and including) '%' with whatever the string I am passing. The error message is not particularly informative though. Any ideas what am I doing wrong?
content = content.replace(/\%.*?\%/, values.first_name);
1 Answer
Jason Anello
Courses Plus Student 94,610 PointsHi Yevgen,
It looks like you've coded a solution to work specifically for the example given. Your code assumes there is only 1 placeholder and that the object passed in has a a property "first_name".
I suspect that the challenge is testing your code for a more general example. There could be several placeholders in the template and the object could have several properties corresponding to those placeholders.
In the previous video you're shown how to use a for in
loop to loop over each property in the object. This way the code can handle as many placeholders as the template may contain.
for (var key in values){ // iterate over each property in the object
content = content.replace(/\%.*?\%/, values[key]); // match the next placeholder and replace it with the value at the current property
}
Also, you've used a regex here which differs from what is taught in that previous video. This code does pass the challenge but it is risky to use that regex and I think the code challenge doesn't have enough test cases to cause it to fail. The order you get the properties in a for in
loop isn't guaranteed. This means they won't necessarily match the order of the placeholders in the template leading to mismatched substitution.
I recommend coding it like the video so that you have a more foolproof and flexible program. Instead of a regex, you can pass in a string that is made up of the current key
surrounded by %
. This insures that the placeholder and property always match up.
for(var key in values){
content = content.replace("%" + key + "%", values[key]); // match the placeholder with the current key and replace it with the value at that current key
}
Y. Kravets
10,350 PointsY. Kravets
10,350 PointsIndeed it looks like I may have misunderstood what was required from me. Thanks for taking time to write such a detailed clarification. Certainly appreciate it a lot.