动态替换字符串中的所有标记实例

时间:2015-11-06 13:36:46

标签: javascript regex meteor

尝试使用Javascript中的RegExp替换电子邮件模板中的每个数据标记。这是一封电子邮件示例:

<h3>Appointment Scheduled</h3>
<p>%clientName%,</p>
<p>Your appointment with %userName% for %serviceName% is scheduled on %appointmentStart%. Please visit the following link if you would like to view or modify your appointment:</p>
<p style="margin-left: 25px;">%appointmentLink%<br></p>

我正在使用Meteor并使用此功能在服务器上执行此操作,我无法弄清楚为什么它不替换每个标记。

prepareEmail : function(templateType, appointmentId) {

var thisUser = Meteor.user();
var message = Emails.findOne({type : templateType, orgId : thisUser.org._id });
var appointment = Appointments.findOne();
var user = Meteor.users.findOne(appointment.userId);
var service = Services.findOne("nNChpXMtYrWsyrqCr");
var client = "Client Name";

var variables = [
{ name: 'userName', value : '%userName%', collection : 'Meteor.users', field : thisUser.profile.name},
{ name: 'serviceName', value : '%serviceName%', collection : 'Services', field : service.name},
{ name: 'serviceDuration', value : '%serviceDuration%', collection : 'Services', field : service.duration},
{ name: 'servicePrice', value : '%servicePrice%', collection : 'Services', field : service.price},
{ name: 'serviceDescription', value : '%serviceDescription%', collection : 'Services', field : service.description},
{ name: 'appointmentStart', value : '%appointmentStart%', collection : 'Appointments', field : appointment.start},
{ name: 'appointmentEnd', value : '%appointmentEnd%', collection : 'Appointments', field : appointment.end},
{ name: 'appointmentLink', value : '%appointmentLink%', collection : 'Appointments', field : appointment._id},
{ name: 'clientName', value : '%clientName%', collection : 'Clients', field : 'name'},
{ name: 'clientPhone', value : '%clientPhone%', collection : 'Clients', field : 'phone'},
{ name: 'clientEmail', value : '%clientEmail%', collection : 'Clients', field : 'email'},
{ name: 'orgName', value : '%orgName%', collection : 'Orgs', field : 'name'},
{ name: 'orgAddress', value : '%orgAddress%', collection : 'Orgs', field : 'address'},
{ name: 'orgPhone', value : '%orgPhone%', collection : 'Orgs', field : 'phone'},
{ name: 'orgEmail', value : '%orgEmail%', collection : 'Orgs', field : 'email'},
];

var emailContent = message.emailContent;
console.log(typeof emailContent)
variables.forEach(function (variable) {
  var match = variable.value;
  var replace = variable.field;
  console.log(match + " --> " + replace);
  replaceAll(emailContent,match,replace);
});

console.log(emailContent);
 }

function replaceAll(str, find, replace) {
  return str.replace(new RegExp(escapeRegExp(find), 'g'), replace);
}
function escapeRegExp(str) {
    return str.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
}

1 个答案:

答案 0 :(得分:1)

只需更换

即可
replaceAll(emailContent,match,replace);

emailContent = replaceAll(emailContent,match,replace);

您忘了保存修改。

请参阅the fiddle