SBB SBB - 1 year ago 63
Javascript Question

Javascript create a mapping of array values

I am working on a project where I give a user the ability to create their own email templates and insert tags into them as placeholder values that will eventually replaced with content.

The tags are in the format of

[FirstName] [LastName]

I am trying to figure out the best approach to create a function that maps these tags to their values.

For example (Psuedo code):

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;

I assume I could do something like the following:

function convertTags(message){

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

return message;

I am just trying to come up with a clean way to do this, preferably in an array/mapping style format that I can easily add to.

Any recommendations on achieving this?

Answer Source

You're on the right lines. You just need to generalise your REGEX to match all params, not specifically 'firstname' or some such other hard-coded value.

Let's assume the replacers live in an object, replacers.

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

And here's our template:

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

For the replacement, we need iterative replacement via a callback:

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, '??'

The value of tmplt is now

This is my template bar etc etc foo - ??