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 trialCristian La Spina
11,829 PointsI don't understand what is wrong with my code
If I run index.js from the command prompt with the command "node index.js", it works just fine but the challenge task continues to refuse and tells me that it's wrong... mysteries of the task challenge...
var utilities = require("./utilities");
var mailValues = {};
mailValues.first_name = "Janet";
var emailTemplate = "Hi %first_name%! Thanks for completing this code challenge :)";
var mergedContent = utilities.merge(emailTemplate, mailValues);
//mergedContent === "Hi Janet! Thanks for completing this code challenge :)";
function merge(content, values) {
content = content.replace("%first_name%", values["first_name"]);
return content;
}
module.exports.merge = merge;
2 Answers
Chris Shaw
26,676 PointsYou have the right idea about how to replace the placeholders but the challenge is asking for you to take the gives values and find them in the string without hardcoding anything.
What does this mean?
We know that values
is an objects and its keys are the name of the placeholders in the template therefore we can iterate over them to automatically search and replace the placeholders.
The simplest way of iterating values
is to use a for...in
loop which gives us access to all the placeholder keys needed for the replacement.
OK! What next?
MDN has a great resource on for...in
loops which I highly recommend you read if you're not too familiar with them.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in
for (var placeholder in values) {
// Replacement code goes here
// content = content.replace(<placeholder>, <placeholder value>);
}
Giving out the answer would be far too simple, instead I have given you the starting point and it's up to you to fill in the blanks. i.e <placeholder>
and <placeholder value>
.
Happy coding!
Cristian La Spina
11,829 PointsAh, ok, I got it! I didn't notice that the string to replace was the same as the property name, just surrounded by "%". Thanks