节点js合并值基本实现

时间:2015-11-29 07:10:42

标签: javascript node.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 个答案:

答案 0 :(得分:1)

你的合并函数不好,它确实很奇怪,如果你传递另一个模板肯定会返回一个奇怪的字符串。您正在用" Hi ...."替换整个输入字符串。字符串,但插入了first_name,所以最后,你的函数太具体了,无法处理额外的参数或其他模板/字符串。



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




试试"运行代码段"按钮。

def self.countries_except_for(user) where.not(user_id: user.id, country: nil).pluck(:country) end 版本,有关信息,最好使用以前的版本。



Profile.countries_except(current_user)