Get Programming with JavaScript - Listing 19.06

Listing 19.06 - Using a while loop with replace

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.");

Further Adventures

Listing 19.06 - Using a while loop with replace - Task 2

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.");