ES6 Template Strings without Indent via tags

ES6 is pretty cool. One new feature is template strings which allow for multiline interpolated strings.

For example, from MDN:

console.log(`string text line 1
string text line 2`);
// "string text line 1
// string text line 2"

They also allow for evaluated variables embedded within the string (again from MDN):

var a = 5;
var b = 10;
console.log(`Fifteen is ${a + b} and\nnot ${2 * a + b}.`);
// "Fifteen is 15 and
// not 20."

The problem is that you may be using these strings within a class that already has indentation.

export class App {
    text =`
       This is an example of what could be considered a 
       "problem" with ES6 multiline strings.
       
       Each of these lines will have 7 characters of whitespace
       at the beginning of the line.`;
    }
}

This is probably not what you want in every situation.

Luckily, ES6 supports something called tagged template strings. Using a special function syntax, you can hook into the template functionality and either change how the template is evaluate or modify the output of the template. You can use these tagged template strings to achieve something like Scala’s stripMargin function. If you’re not familiar with stripMargin, you basically put a pipe (the | character) at the start of the line and indentation before the pipe is ignored. You can achieve this with tag template that performs a regex replace:

Here’s how this baby works:

See the Pen xZZmVV by Jim Schubert (@jimschubert) on CodePen.

Related Articles