Javascript usage of ${variable}

Asked

Viewed 3,945 times

8

I was reading this article on AJAX when I came across this way of using a variable inside a string:

let cep = document.getElementById('cep').value;

axios.get('http://api.postmon.com.br/v1/cep/${cep}')... // o ${cep} me lembra a sintaxe do php

I was intrigued because I’ve never seen this way of using a variable, can tell me if it uses a library for this type jQuery or has native support of Javascript?

Note: I couldn’t find a right term to search in Google so I resorted here.

2 answers

10


This is a specification of Ecmascript introduced in its version 5 as strings template, and from version 6 is called literals template.

Its main function of literals template is the ease to mount string, can make expressions or use variables within a string, making it easy to read the same.

For example, instead of you concatenating it directly in the traditional way:

var nome = 'João';
var string = 'Olá! ' + nome + ', você está usando o StackOverflow!';

alert(string);

You can do it this way:

var nome = 'João';
var string = `Olá!, ${nome}, você está usando o StackOverflow!`;
alert(string);

In this case, the expression ${nome} will be replaced by the contents of the corresponding variable, making it much easier for you to read and maintain.

For more information on literals template see this documentation.

But beware, some versions of browsers may not support this feature. See here the full list of supported versions.

For technical documentation (in English), see here on the official website of Ecmascript.

6

The name of this resource is Template string.

Template String

Template literals are string literals that allow embedded expressions. You can use multi-line string and string interpolation with them. They were called "template strings" in versions prior to the ES2015 specification.

Syntax

`corpo de texto`
`texto linha 1
 texto linha 2`
`texto string ${expression} texto string`
tag `texto string ${expression} texto string`

Browser other questions tagged

You are not signed in. Login or sign up in order to post.