jskatas.org Continuously Learn JavaScript. Your Way.

Template strings: raw property

The raw property can access the string without processing escape sequences.

Using raw property in a tagged template function

What? The property raw is on the array that contains all string parts of a template string

WHEN reading .raw of the strings (the 1st parameter) THEN it returns an array of all raw strings of the template
// `strings` contains only the pure strings, not the expressions! // This means the ${2} and ${3} are not contained in `strings`. function tag(strings) { return strings.___; } assert.deepEqual(tag`1${2}\n${3}4`, ['1', '\\n', '4']);
WHEN reading the raw value of a backslash THEN this returns the text as written in the original string, not the character only
function tag(strings) { return {string: strings[0], rawString: strings[0]}; } // Note: the four backslashes below are needed in order to escape each backslash, so \ in a string must always be \\ // otherwise it is seen as a character to escape the following character, see e.g. \n which is a line break, without the // leading \ it would just be an n. assert.deepEqual(tag`\\`, {string: '\\', rawString: '\\\\'});
WHEN analyzing the tag-function arguments THEN the function signature is much like the one of String.raw
//: {"jskatas":{"terms": ["function signature", "tag-function"]}} function tag({raw}, ...values) { return [{raw}, ...values]; } const signature = [{raw: ['one', '\\n']}, 0]; assert.deepStrictEqual(tag`one${0}\n`, signature); assert.deepStrictEqual(String.raw(...signature), 'one0\\n');

using raw in a tagged template

WHEN using .raw on a "normal" character THEN this is the character itself
function tagged(string) { return string.raw[0][0]; } assert.equal(tagged`AB`, 'B');
WHEN reading the first character of the raw value of a line break THEN this is a backslash
function firstCharEntered(strings) { var lineBreak = strings.raw; return lineBreak; } assert.equal(firstCharEntered`\n`, '\\');

Links

Description of `raw` property of tagged template strings.
Describing the raw behavior.
The JS engine internal abstract operation `GetTemplateObject` describes how the template object, that is passed to the tag-function is created, see esp. the adding of the `raw` property onto the array here (item: 14. Perform ! DefinePropertyOrThrow(template, "raw"...).

Required Knowledge

Related Katas

Template strings

String API

Difficulty Level

EXPERT

First Published

18 March 2015

Stats

5 tests to solve