Solution Review: Tagged Template
Let’s discuss the solution to the tagged template challenge given in the previous lesson.
We'll cover the following...
Solution
We will review the following solution step-by-step.
Press + to interact
'use strict';const stripMargin = function(texts, ...expressions) {const exceptLast = expressions.map(function(expression, index) {return `${texts[index]}${expression.toString().toUpperCase()}`;}).join('');const result = `${exceptLast}${texts[texts.length - 1]}`;return result.replace(/[\n][\t\s]+(\w)/g, ' $1').trim();};const name = 'Jane';const processed = stripMargin` This is for${name} and it needs to bedelivered by December 24th.`console.log(processed);//This is for JANE and it needs to be delivered by December 24th.
Explanation
There are two main functionalities that tag stripMargin
has to implement to get the desired output.
- Convert all expressions to upper case
- Remove all leading spaces and indentations on the new lines
So, let’s start with the first one.
Converting expressions
In the function definition at line 3, we are taking two parameters:
texts
expressions
expressions
The ...