jskatas.org Continuously Learn JavaScript. Your Way.

Template strings: tagged template strings

Advanced form of template strings.

Tagged template strings, are an advanced form of template strings

Syntax: prefix a template string with a function to call (without "()" around it)
function tagFunction(s) { return s.toString(); } var evaluated = tagFunc `template string`; assert.equal(evaluated, 'template string');

the tag function can access each part of the template

the 1st parameter receives only the pure strings of the template string

the strings are an array
function tagFunction(strings) { return strings; } var result = 'template string'; assert.deepEqual(result, tagFunction`template string`);
expressions are NOT passed to it
function tagFunction(strings) { return strings; } var tagged = tagFunction`one${23}`; assert.deepEqual(tagged, ['one', 'two']);

the 2nd and following parameters contain the values of the processed substitution

the 2nd parameter contains the first expression`s value
var one = 1; var two = 2; function firstValueOnly(strings, first_value) { return firstValue; } assert.equal(firstValueOnly`uno ${one}, dos ${two}`, 1);
the 3rd parameter contains the second expression`s value
var one = 1; var two = 2; function secondValueOnly(strings, firstValue, ____) { return secondValue; } assert.equal(secondValueOnly`uno ${one}, dos ${two}`, 2);
using ES6 rest syntax, all values can be accessed via one variable
var one = 1; var two = 2; var three = 3; function allValues(stringsArray, ...allTheValues) { // using the new ES6 rest syntax return; } assert.deepEqual(allValues`uno=${one}, dos=${two}, tres=${three}`, [1, 2, 3]);

Links

Description of tagged template strings.

Required Knowledge

Related Katas

Template strings

String API

Difficulty Level

INTERMEDIATE

First Published

17 March 2015

Stats

6 tests to solve