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)
That's pretty easy to do with one regex replacement using a callback for the substitution text:
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}}
: