Replacing multiple occurrences of dynamic strings?

1.1k Views Asked by At

Not sure if I could explain better in the title, but ill explain here better. I am trying to create a function that will act as a simple "templater". I feed it a string with certain tags "{{name}}" and it will replace it with a certain string.

here is what i have so far:

Calling the function:

loadTemplate("<div>{{name}}, {{anotherString}}</div>", {
    name: "Hunter",
    anotherString: "is amazing!!!!" 
});

The function:

// Created this to make my life easier :)
function loadTemplate(template, data) {
    var tags = template.split("{{").pop().split("}}").shift();
    console.log(tags); // This only gives me the last occurrence.
}

How would I loop through all the occurrences of {{variable}} in my string so i can replace it with the associated data?

Similar to Handlebars.js (I am wanting a SUPER lightweight and fast function, not an entire plugin)

3

There are 3 best solutions below

7
On BEST ANSWER

That's pretty easy to do with one regex replacement using a callback for the substitution text:

function loadTemplate(template, data) {
    return template.replace(/\{\{(\w+)\}\}/g, function(match, key) {
        return data[key];
    });
}

alert(loadTemplate("<div>{{name}}, {{anotherString}}</div>", {
    name: "Hunter",
    anotherString: "is amazing!!!!" 
}));

The pattern is \{\{(\w+)\}\}, meaning {{, followed by a captured word, followed by }}. A word is any sequence of alphanumeric characters and underscores.

You can replace \w+ with .+? if you want to be able to use any key value (like, with spaces for instance) which doesn't contain }}:

function loadTemplate(template, data) {
    return template.replace(/\{\{(.+?)\}\}/g, function(match, key) {
        return data[key];
    });
}

alert(loadTemplate("<div>{{The Name}}, {{Another $tring}}</div>", {
    "The Name": "Hunter",
    "Another $tring": "is amazing!!!!" 
}));

1
On

Do a search/replace for each key in the data object:

function loadTemplate(template, data) {
  var RE, d;
  for(d in data) {
    RE= new RegExp('{{'+d+'}}', 'g');
    template= template.replace(RE, data[d]);
  }
  console.log(template);
}

loadTemplate("<div>{{name}}, {{anotherString}}</div>", {
  name: "Hunter",
  anotherString: "is amazing!!!!" 
});

0
On

I like your 'split' idea, I say stick with it:

window.loadTemplate = function(template, data) {
    var i = 0;
    var bool = true;
    while (bool) {
        try {
        var tags = template.split("{")[i+2].split("}")[0];
        alert(tags);
        i+=2;
        } catch (e)
        {
            bool = false;
        }
    }
}
td {
    border: black solid 1px;
}
<button type="button" onclick="loadTemplate('<div>{{name}}, {{anotherString}}</div>', {name: 'Hunter', anotherString: 'is amazing!!!!' })">Load Template</button>