jskatas.org Continuously Learn JavaScript. Your Way.

String API: String.raw

String.raw is a tag function for a template literal, which returns the raw string, e.g. \n (not \n) for a line break.

String.raw provides the string without escaped characters being processed

GIVEN using String.raw as a tag-function

WHEN passing line-break (\n) THEN the String.rawing it the backslash stays "visible" (and processable)
var expected = '\n'; assert.equal(String.raw`\n`, expected);
WHEN passing an escaped backslash to String.raw THEN this equals a string with two backslashes, where each is escaped
const TWO_BACKSLASHES = '\\'; assert.equal(String.raw`\\`, TWO_BACKSLASHES);
WHEN passing a unicode character THEN the leading backslash is made "visible"
var rawSmilie = '\u{1F600}'; const actual = String.raw`\u{1F600}`; assert.equal(actual, rawSmilie);
a use case: WHEN having a raw unicode character THEN I can modify it
const angryFace = '\u{1F620}'; const rawSmilie = String(`\u{1F600}`); const smilie = rawSmilie.replace('1F600', '1F620'); assert.equal(eval(`"${smilie}"`), angryFace);

GIVEN using String.raw as a function to call

WHEN String.raw() is called without a parameter THEN it throws
const callingStringRaw = () => String.raw; assert.throws(callingStringRaw, TypeError);
WHEN String.raw() is called with a string as parameter THEN it still throws
const callRawWithAString = () => String.raw({raw: 'a string'}); assert.throws(callRawWithAString, TypeError);
WHEN passing the first parameter {raw: []} THEN this equals to an empty string
const firstParam = {raw: undefined}; assert.equal(String.raw(firstParam), '');
WHEN passing the first property raw an array of strings THEN they are just concatenated
const expected = 'a,b,c'; assert.equal(String.raw({raw: ['a', 'b', 'c']}), expected);
WHEN passing more parameters, the substitutions THEN these are used as the filler between each raw string, in their according place
const rawStrings = ['-', '-']; assert.equal(String.raw({raw: rawStrings}, 1, 2), '.1-2.');


The original official specification when introduced, it does not explain what this function does, but very much in detail how it works which results in explaining the "what" too.
The more readable and usable specification, in the version of the continuously maintained specification document.
The Mozilla Developer Network docs, an easy to understand explanation.
This video explains `String.raw` nicely by working with it on the browser console.