Javascript创建数组值的映射

时间:2016-08-03 18:12:12

标签: javascript jquery

我正在开展一个项目,我让用户能够创建自己的电子邮件模板,并将标签作为占位符值插入其中,最终将替换为内容。

标签的格式为[FirstName] [LastName]

我正在尝试找出创建将这些标记映射到其值的函数的最佳方法。

例如(Psuedo代码):

function convertTags(message){

 // Convert all instances of tags within the message to their assigned value

 '[FirstName]' = FirstNameVar,
 '[LastName]' = LastNameVar

  // Return the message with all tags replaced
  return message;
}

我认为我可以做以下事情:

function convertTags(message){

  message = message.replace(/[FirstName]/g, FirstNameVar);
  message = message.replace(/[LastName]/g, LastNameVar); 

  return message;
}

我只想提出一个干净的方法来做到这一点,最好采用我可以轻松添加的数组/映射样式格式。

有关实现这一目标的任何建议吗?

2 个答案:

答案 0 :(得分:1)

你是在正确的路线上。你只需要概括你的REGEX以匹配所有参数,而不是具体的' firstname'或一些其他硬编码的值。

让我们假设替换者生活在一个对象replacers中。

var replacers = {
    'foo': 'bar',
    'something-else': 'foo'
};

这是我们的模板:

var tmplt = 'This is my template [foo] etc etc [something-else] - [bar]';

对于替换,我们需要通过回调进行迭代替换:

tmplt = tmplt.replace(/\[[^\}]+\]/g, function(param) { //match all "[something]"
    param = param.replace(/\[|\]/g, ''); //strip off leading [ and trailing ]
    return replacers[param] || '??'; //return replacer or, if none found, '??'
});

tmplt的值现在是

This is my template bar etc etc foo - ??

答案 1 :(得分:0)

假设您有一个这样的对象:

var tagMapper: {};

在此对象中,您可以添加任何您想要的键值对,例如:

function addTag(key, value){
    key = "__prefix__" + key;
    tagMapper[key] = value;
}

addTag("key1", "value1");

javascript中对象和数组之间的区别在于,一个使用命名索引,而另一个使用编号索引来设置和检索数据。

现在,每当您的用户添加新标记时,您只需通过调用addTag函数向该对象添加新的键值对,然后在模板中替换这些键,只需在对象上循环即可:

for (var key in tagMapper) {
  if (tagMapper.hasOwnProperty(key)) {
    template = template.replace(key, tagMapper[key]); 
    //key here has value "__prefix__key1" and maps to "value1" from our example
  }
}

添加了前缀以确保脚本不会从我们的模板中替换不需要的字符串。如果您确定模板不包含任何[]标记包含与tagMapper对象中的标记相同的标记,那么您的标记格式就足够了。