Listing 19.06 - Using a while loop with replace
JS Bin
var template = "{{title}} by {{author}}. Follow {{author}} {{social}}";
var filled = template;
console.log("Starting replacement...");
while (filled.indexOf("{{author}}") !== -1) {
filled = filled.replace("{{author}}", "Oskar");
console.log(filled);
}
console.log("...replacement finished.");
Listing 19.06 - Using a while loop with replace - Task 2
- Create your own replace function. Move the while loop into your function. The function should accept three arguments: template, placeholder and data.
function replace(template, placeholder, data) {
var filled = template;
while (filled.indexOf(placeholder) !== -1) {
filled = filled.replace(placeholder, data);
}
}
// test the function
var template = "{{title}} by {{author}}. Follow {{author}} {{social}}";
console.log("Starting replacement...");
console.log(replace(template, "{{author}}", "Oskar"));
console.log("...replacement finished.");