Learn about Template Literals in JavaScript

Tram Ho

1. Introduction

In ES6 2015, we added template literals (string characters) to JavaScript. Template literals are a new form of string creation in JavaScript, adding many powerful new features, such as creating easier multi-line strings and using placeholders to embed expressions into strings. In addition, an advanced feature called tagged template literals allows you to perform operations on expressions in a string. All of these features increase the options for manipulating strings, allowing you to easily create dynamic strings that can be used for URLs or custom functions in HTML components.

In this article, you’ll learn the difference between single / double quotes and template literals, different ways to declare strings of different shapes, including multi-line strings and Dynamic strings vary depending on the value of a variable or expression. You will then learn about tagged template literals and see some practical examples of projects that use them.

2. Chain initialization

This section will show the ways of declaring strings with single and double quotes and then will show how to do the same with template literals.

In JavaScript, a string can be written with single quotes (”) or double quotes (“”) as follows:

There is no big difference in JavaScript between strings that use single or double quotes, unlike other languages ​​that can allow interpolation in one type of string but not another. In this context, interpolation refers to evaluating a placeholder as a dynamic part of a string.

The use of single / double quote sequences mostly depends on personal preferences and conventions, but they can be used in combination, each of which needs to escape its own type of quote:

On the other hand, template literals are written by enclosing a string with an accent (`):

Template literals can do everything normal strings can, so you can replace all the strings in your project with them and have the same functionality. However, the most common convention is to use templates only when using the additional capabilities of those templates and consistently use parentheses or quotes for all other simple strings. Following this standard will make your code more readable if tested by other developers.

Now that you’ve seen how to declare strings with parentheses, quotes and backticks, you can move on to the first advantage of template literals: writing multi-line strings.

3. Multi-line Strings

In this section, you will first run through how multi-line strings are declared before ES6, and then see how template literals make this easier.

Initially, if you want to write a multi-line string, you will use the concatenation operator (concatenation operator). However, this is not always a simple process. For example :

This may allow you to split the string into smaller lines and pass it across multiple lines in the editor, but it has no effect on the string output. In this case, all strings will be on one line and not separated by carriage returns or spaces. If you have logged in the address to the console, you will get the following:

The backslash character () can be used to continue strings across multiple lines:

This will retain any indentation as a space, but the string will still be on one line in the output:

Using new line characters ( n), you can create a real multi-line string:

Open the console and you will see:

However, using newline characters to specify multi-line strings can be counterproductive. In contrast, creating a multi-line string with template literals can be much simpler. No need to append, use newline characters or use backslashes. Just press enter and write the string on multiple lines active by default:

The output will be the same as the input:

Any indentation will be preserved, so it is important not to indent any additional lines in the series if that is not desirable. For example :

Although this type of writing may make your code more readable, the output will be a bit odd:

With multi-line strings resolved, the next section will be how expressions are interpolated into their values ​​with different string declarations.

4. Interpolation expression

Before ES6, concatenation was used to create dynamic strings with expressions or variables:

Run in the console:

With template literals, an expression can be embedded in a placeholder. A placeholder is denoted by $ {} , with anything in curly braces being considered JavaScript and everything outside the parentheses is considered a string:

Print out in console:

A common example of embedding values ​​in strings might be to generate dynamic URLs. It seems a bit bulky. For example, the following declares a function to create an OAuth access string:

Test run in console:

Using string interpolation, you no longer have to keep track of opening and closing of strings and the position of the join operator. For example :

The result is similar to the above string concatenation:

The trim() used to eliminate terminal whitespace, for example:

The following results :

The whole expression can be interpolated, not just variables, such as in this example the sum of two numbers:

This can be particularly useful with ternary operators, which allow conditions in a string:

Now you have an idea of ​​how template literals can be useful when used to interpolate expressions. The next section takes this one step further by examining Tagged Template Literals to work with the expressions passed to the placeholder.

5. Tagged Template Literals

An enhanced feature of Template Literals is the use of Tagged Template Literals, sometimes called templae tags. Template tags start with the template parsing function, giving you more control over manipulating and returning dynamic strings.

In this example, you will create a template function to use as a function that works on a tagged template. Character strings are the first parameter of the function, the strings are named here, and any expressions interpolated in the string are packed into the second parameter with the remaining parameters. You can control parameters to see what they will contain:

Use the function tag as a tagged template function and analyze the string as follows:

Open the console and run:

The first parameter, strings , an array string consists of:

  • “This is a string with”
  • “and”
  • “and”
  • “interpolated inside.”

There is also a raw attribute available on this argument at String.raw , which contains the string without any strings being processed. For example, / n will be just the / n character and will not be included in the new line.

The second parameter, ...expressions , is the remaining parameter array that includes all the expressions:

  • true
  • false
  • 100

The strings of characters and expressions passed as parameters to the tagged funciton tag. Note that the tagged template does not need to return a string; It can work on those values ​​and return any kind of value. For example, we can have a function that ignores everything and returns null, as in this returnNull function:

An example of an action that can be performed in tagged templates is applying some changes to both sides of each expression, such as if you want to wrap each expression in the HTML tag. Create a bold function, add <strong> and </ strong> to each expression:

There are a few examples of tagged template literals in popular JavaScript libraries. The Graphql tag library uses a gql tagged template to parse GraphQL query strings into an abstract syntax (AST) that GraphQL understands:

Another library that uses tagged template functions is styled components, allowing you to create new React components from regular DOM components and apply additional CSS styles to them:

The built-in String.raw method can also be used on tagged text to prevent any string from being processed:

6. Conclusion

In this article, you looked at csingle- and double-quoted string literals and you learned about template literals and tagged template literals. Template literals make many common string tasks simpler by interpolating expressions in strings and creating multi-line strings without any concatenation or escape. Template tags are also a useful enhancement of template literals that many popular libraries have used, such as GraphQL and styled-components .

To learn more about strings in JavaScript, read How to work with strings in JavaScript and How to index, split, and manipulate strings in JavaScript .

Source: https://www.taniarascia.com/understanding-template-literals/

Share the news now

Source : Viblo