2015-11-29 53 views
0

我试图做类似下面的,但合并功能与行的问题节点JS合并值基本实行

content = content.replace(content, "Hi" + values.first_name + "! Thanks for completing this code challenge :)");

文件名:app.js

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

文件名:utilities.js

function merge(content, values) { 

    content = content.replace(content, "Hi" + values.first_name + "! Thanks for completing this code challenge :)"); 
    return content; 
} 


module.exports.merge = merge; 
+1

我觉得有一个错字在你的'合并()function'。这可能,应该已经'content = content.replace(“%first_name%”,“嗨”+ values.first_name +“!感谢您完成此代码的挑战:)”);' – IronGeek

+0

我试过这个。但这也不正确。 – kushalvm

+0

这工作对我来说:'content.replace(“%FIRST_NAME%”,values.first_name);' – Ziki

回答

1

你的合并函数不好,它做了一个奇怪的事情,如果你传递另一个模板,肯定会返回一个奇怪的字符串。你用“Hi ....”字符串替换了整个输入字符串,但是最后插入了first_name,你的函数太具体了,不能处理额外的参数或另一个模板/字符串。

function merge(content, values) { 
 
    // loop over all the keys in the values object 
 
    Object.keys(values).forEach(function(key) { 
 
    // look for the key surrounded by % in the string 
 
    // and replace it by the value from values 
 
    content = content.replace('%' + key + '%', values[key]); 
 
    }); 
 
    return content; 
 
} 
 

 
var mailValues = {}; 
 
mailValues.first_name = "Janet"; 
 
mailValues.last_name = "Doe"; 
 
var emailTemplate = "Hi %first_name% %last_name%! Thanks for completing this code challenge :)"; 
 
var mergedContent = merge(emailTemplate, mailValues); 
 

 
document.write(mergedContent);

试 “运行的代码片断” 按钮。

for ... in版本,信息,更好地使用以前的版本。

function merge(content, values) { 
 
    // loop over all the keys in the values object 
 
    for (var key in values) { 
 
    // look for the key surrounded by % in the string 
 
    // and replace it by the value from values 
 
    content = content.replace('%' + key + '%', values[key]); 
 
    } 
 
    return content; 
 
} 
 

 
var mailValues = {}; 
 
mailValues.first_name = "Janet"; 
 
mailValues.last_name = "Doe"; 
 
var emailTemplate = "Hi %first_name% %last_name%! Thanks for completing this code challenge :)"; 
 
var mergedContent = merge(emailTemplate, mailValues); 
 

 
document.write(mergedContent);

+0

它的工作。但你也可以用“for in”循环来做到这一点。请不要编辑这一个。至少我会学习这两种方法。 – kushalvm

+0

这对我来说也适用。 '为(在值VAR键){ 含量= content.replace( “%” +键+ “%”,数值[键]); } ' – kushalvm

+0

我也有你的解决方案。谢谢 ! – kushalvm