Different uses for Template Literals in JavaScript
By: Kesk - -
Tags: Javascript Tips, Template Literals, Javascript Development, Web Development, JavaScript

Different uses for Template Literals in JavaScript

You can use them for more things than you think

Two monitors with background code

Introduced in ES2015 edition of the ECMAScript specification (ES6) Template Literals(or the old name for template literals: Template strings) offer a new way of making strings in JavaScript that add a lot of powerful new capabilities, such as using placeholders to embed expressions in a string and generating multiline strings more easily.

The syntax is straightforward, just use backticks instead of double or single quotes:

const literal = `hello!`

They provide several features that regular strings built with quotes do not, in particular:

They provide a simple way to include variables and expressions in strings.

Template literals give a great syntax to define multiline strings.

They allow creating DSLs using template tags.

It is more straightforward to format a string because the format remains as we wrote it.

Index:

Declaring Strings

Multiple lines with interpolate expressions

Tagged Templates

Shell commands

Embedded HTML

Raw String

Customizable regexp

Let’s see some useful examples.

Declaring Strings

In JavaScript, you can write a string using single quotes (‘ ‘):

const single = 'Hello'

Or using double quotes (“ “):

const double = "Hello"

There is no significant difference in JavaScript between single- or double-quoted strings.

Now, if you want to include an expression you can do:

let name= "Kesk"; const hello = "Hello" + name + "!"; console.log(hello);

//Hello Kesk

But it gets complicated if you want to format a text or you have multiples expressions inside it:

To achieve this:

//Hello Kesk!

//.This is a multiline message

//that maintains the format

We can do:

const name = "Kesk" const s1 = "Hello " + name + "!

"

+ ".This is a multiline message

"

+ "that maintains the format

"; console.log(s1);

Result in chrome dev tools.

But it’s more straightforward if you use ES6 String literals:

Multiple lines with interpolate expressions

As you can view in this example, we include a variable within our text. Also, it keeps the format we give it, and the result is cleaner and more evident.

We use backticks to write a string literal: ` the string with expressions.` To interpolate variables and expressions, you can do by using the ${…} syntax.

const name = 'Kesk'; console.log(`Hello ${name}!

this is a multiline message

that maintains the format`); //Result:

//Hello Kesk!

//this is a multiline message

//that maintains the format

Result in chrome dev tools.

Other uses cases:

Tagged Templates

Thanks to Template Literals, you can create Tagged Template Literals, witch is string literals allowing embedded expressions. You can use multiline strings and string interpolation features with them.

A tagged template begins with a tag function that parses a template literal, returning a dynamic string. The first argument of a “tag function” is an array containing all the string literals. The remaining arguments are expressions.

let name = 'Kesk';

let gender = 'female';

function greetingTag (strings, name, gender) { //strings is an array.

console.log(strings); //"Hello"

let str0 = strings[0];

//"you are a beutiful"

let str1 = strings[1];



let text = gender === 'female' ? 'girl' : 'man'



//Return a string built

//using a template literal

return `${str0}

${name} ${str0} ${str1}:

${text}

`;

} let result = greetingTag`Hello ${name} you are a beatiful ${gender}`; console.log(result);

Result of executing greetingTag in chrome dev tools.

Other things that you can do with ES6 template literals:

Shell commands

With sh.js and template literals, you can write and execute shell commands.

sh.js is a JavaScript library for Unix shell scripting running on node.js.

You need to write a JavaScript file and run it with node.js

npm install sh

ls.js

let sh = require('sh'); let ls = sh`ls -a`;

>node ls.js

Embedded HTML

With lit-html and JavaScript template literals, you can quickly write HTML templates.

import {html} from 'lit-html'; //A lit-html template

//uses the `html`

//template tag:

html`<div>

<a href="${url}">${name}</a>

</div>`

...

Raw String

Raw method of template literal allows access of raw strings as they were entered, without processing escape sequences.

const value= String.raw`this is a multiline message

that maintains the format.

Escapes are not interpreted,



is not a newline.`; console.log(value); //this is a multiline message

// that maintains the format.

// Escapes are not interpreted,

//

is not a newline.

Result of executing our String.raw function in chrome dev tools.

Customizable regexp

You can use too a RegExp constructor to build a regexp using a literal template:

const regex = new RegExp(String.raw`write pattern as in regex literal without delimiters`)

Or to build a complex RegExp with tagged template and template literals:

// tagged template function

const rgExpTag = (str0, str1) => {

return new

RegExp(`${str0.raw[0]}${str1}${str0.raw[1]}`, 'gi')

} const regex = "~!@#$%^&*()_" ;

const rawData= "$100.50$$$$"; const number =

rawData.replace(rgExpTag`[${regex}]`, ''); console.log(number)

//100.50

Result of executing our rgExpTag function in chrome dev tools.

Conclusion

With Template literals, work with strings is more natural, and you can create strings and interpolate expressions in strings without any concatenation or escaping. Template tags are also a useful feature that many popular libraries use, but as you can see, you can use template literals for other useful things.

Thank you very much for reading this article. I hope it is useful for you! Take care!