Usage of the Backtick Character (') in JavaScript

Back-tick vs single quote in js

the back-tick allows you to use string templating for example:

var value = 4;
var str = `text with a ${value}`
// str will be : 'text with a 4'

for " vs ' I say look at this post: https://stackoverflow.com/a/9959952/6739517

As for performance, it seems like it would be the same if you are just using back-ticks for plain strings. However when building strings it looks like concatenation is still the way to go. Take a look here:

2018 update: It seems that ES6 string templating can be faster than concatenation in some cases. Take a look at the following post for some hard numbers:

Are ES6 template literals faster than string concatenation?

2020 update: Generally speaking you should not be worried about performance when considering which type of quotation to use. There might be tiny differences but as many have pointed out these are such tiny improvements you are likely better off optimizing your code rather than considering which character to use. That said, this doesn't really answer the question of consistency. For me, I generally follow Airbnb's style guide. That is strings are always declared with single quotes (') unless you need to build a string then you should avoid concatenation and only use string templating with backticks (`). Finally, double quotes are reserved for JSON and HTML.

Should we use backticks to quote string literals now?

Using Backticks for Strings allows to create Template Strings.

const create = word => `Hello ${word}`

console.log(create("World")); // Hello World

So this is a cleaner way to create/interpolate Strings. Since the transpiler/interpreter will turn that back into something like: "Hello" + word the impact on Performance should depend on the number of Strings to combine and the overall length of the String.

No matter which »type« of String you chose if you need the quoting characters in it, you need to escape them:

console.log(```) // SyntaxError
console.log(`\``) // `

So all in all, template Strings are great for templates, so use them for it if you like, but it wont make any difference, when it comes to escaping, plus, you have to escape $ signs, too.

Use of apostrophe vs single quote/backtick

The backticks are necessary for the string interpolation to work. This is an ES6 feature called template interpolation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals.

Sometimes it will be available to you, but it is still far from widespread in terms of browser support https://caniuse.com/#feat=template-literals. Get familiar with it and use it when you can!

Multiple use of backticks within Javascript

As you know the use of " & ' should corresponded to each other

Double quotes around attribute values are the most common in HTML, but single quotes can also be used.

In some situations, when the attribute value itself contains double quotes, it is necessary to use single quotes:

<p title='John "ShotGun" Nelson'>

Or vice versa:

<p title="John 'ShotGun' Nelson">

The backslash (\) escape character turns special characters into string characters .

If there are extra symbols in between you can use \ backslash before them so that they don't interfere with the code and treated as symbols like this :

<p title="John \'ShotGun\' Nelson you\'re a good\\bad person">

It will be displayed like this :

John 'ShotGun' Nelson you're a good\bad person

Refer to this for more about backslash

When should I use double or single quotes in JavaScript?

The most likely reason for use of single vs. double in different libraries is programmer preference and/or API consistency. Other than being consistent, use whichever best suits the string.

Using the other type of quote as a literal:

alert('Say "Hello"');
alert("Say 'Hello'");

This can get complicated:

alert("It's \"game\" time.");
alert('It\'s "game" time.');

Another option, new in ECMAScript 6, is template literals which use the backtick character:

alert(`Use "double" and 'single' quotes in the same string`);
alert(`Escape the \` back-tick character and the \${ dollar-brace sequence in a string`);

Template literals offer a clean syntax for: variable interpolation, multi-line strings, and more.

Note that JSON is formally specified to use double quotes, which may be worth considering depending on system requirements.

{} vs. ${} in and ` vs. ' (backtick vs quote)

The `` and $ combination is a way to concatenate strings that's easier to read than the old way of using +.

For example say you have obtained the users firstname through some input you might output some string like
Hi There Mark!
where Mark is the users name.
You can do this with either
"Hi There" + user.firstname + "!"
or
`Hi There ${user.firstname}!`.

How do I add a backtick to a regex on a range of characters matching in JavaScript?

Your Answer(s)

First off, the regular expression does actually work, just not how you think. I'll get to that later, under the horizontal rule below.

Your issue is not with the backtick, but with the hyphen before it. Since you are using a hyphen to create your (a-z) and (A-Z) ranges then you must be aware that the hyphen can be a special character within a "character class" (the name for the characters contained in the square brackets) to create a range between two valid characters. However, your last three characters are also creating a range between a space and the backtick ( -`) instead of searching for the hyphen and backtick explicitly.

So, if you want to look for a hyphen specifically you need to do one of the following:

  1. Don't put it between two valid characters. This means, place it at the beginning, at the end, after another range, etc.
  2. Escape it.

Here are some examples, and a fixed up jsfiddle (http://jsfiddle.net/a4vGA/63/):

// Personally, I like #2. Escaping the hyphen just reads much nicer to me:
/^[a-zA-Z' \-`]+$/ // The searchable hyphen char is escaped, breaking the range.

// But any of these all make the searchable hyphen work without escaping:
/^[a-zA-Z' `-]+$/ // The searchable hyphen char is last
/^[-a-zA-Z' `]+$/ // The searchable hyphen char is first
/^[a-z-A-Z' `]+$/ // The searchable hyphen char is between two ranges and,
// therefore, cannot create a range
/^[a-zA-Z-' `]+$/ // The searchable hyphen char is after a range and and,
// therefore, cannot create a range
// etc.

Any of the above will answer your question. You can stop reading here!


Why did it work before?

Your problem was interesting since your pasted regular expression in your question does actually work with your pasted string asdf-'`.

/^[a-zA-Z ' -`]+$/.test("asdf-'`") // true; but not why you may think.

(Note: Your jsfiddle from your comments simply had a typo from your pasted regex in the question accidentally omitting the backtick which was causing it to fail with your test string.)

So then, as we covered above, if the hyphens for this expression are creating three sets of ranges and NOT searching explicitly for the hyphen character, why does it still work? Let's break down the expression to see what's going on.

Your pasted expression ^[a-zA-Z ' -`]+$ will match any series of characters from the start of your line to the end that match:

  • (a-z) as a range, or any of the following characters: abcdefghijklmnopqrstuvwxyz
  • (A-Z) as a range, or any of the following characters: ABCDEFGHIJKLMNOPQRSTUVWXYZ
  • ( ) a space character
  • (') a single quote character
  • ( -`) a space to backtick as a range, or any of the following characters: !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_ `

As you can see, the last three characters ( -`) are creating a range that spans from unicode 0020 (space) to 0060 (backtick) and includes all numbers, capital letters, some special characters and... the hyphen itself! This is why your your string (asdf-'`) actually does match.

Unfortunately, so do many other strings containing any of those characters: 12ab34$!-'`, #!/a b?&, etc.

/^[a-zA-Z ' -`]+$/.test("asdf-'`")   // true
/^[a-zA-Z ' -`]+$/.test("!@#-456") // true
/^[a-zA-Z ' -`]+$/.test("012#$%678") // true
/^[a-zA-Z ' -`]+$/.test("<a:5:c>") // true

So, yeah, make sure to escape (or move your hyphen as described above the horizontal rule) to avoid creating a range with it!

When to use single quotes, double quotes, and backticks in MySQL

Backticks are to be used for table and column identifiers, but are only necessary when the identifier is a MySQL reserved keyword, or when the identifier contains whitespace characters or characters beyond a limited set (see below) It is often recommended to avoid using reserved keywords as column or table identifiers when possible, avoiding the quoting issue.

Single quotes should be used for string values like in the VALUES() list. Double quotes are supported by MySQL for string values as well, but single quotes are more widely accepted by other RDBMS, so it is a good habit to use single quotes instead of double.

MySQL also expects DATE and DATETIME literal values to be single-quoted as strings like '2001-01-01 00:00:00'. Consult the Date and Time Literals documentation for more details, in particular alternatives to using the hyphen - as a segment delimiter in date strings.

So using your example, I would double-quote the PHP string and use single quotes on the values 'val1', 'val2'. NULL is a MySQL keyword, and a special (non)-value, and is therefore unquoted.

None of these table or column identifiers are reserved words or make use of characters requiring quoting, but I've quoted them anyway with backticks (more on this later...).

Functions native to the RDBMS (for example, NOW() in MySQL) should not be quoted, although their arguments are subject to the same string or identifier quoting rules already mentioned.

Backtick (`)
table & column ───────┬─────┬──┬──┬──┬────┬──┬────┬──┬────┬──┬───────┐
↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓
$query = "INSERT INTO `table` (`id`, `col1`, `col2`, `date`, `updated`)
VALUES (NULL, 'val1', 'val2', '2001-01-01', NOW())
";
↑↑↑↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑↑↑↑↑
Unquoted keyword ─────┴┴┴┘ │ │ │ │ │ │ │││││
Single-quoted (') strings ───────────┴────┴──┴────┘ │ │ │││││
Single-quoted (') DATE ───────────────────────────┴──────────┘ │││││
Unquoted function ─────────────────────────────────────────┴┴┴┴┘

Variable interpolation

The quoting patterns for variables do not change, although if you intend to interpolate the variables directly in a string, it must be double-quoted in PHP. Just make sure that you have properly escaped the variables for use in SQL. (It is recommended to use an API supporting prepared statements instead, as protection against SQL injection).

// Same thing with some variable replacements
// Here, a variable table name $table is backtick-quoted, and variables
// in the VALUES list are single-quoted
$query = "INSERT INTO `$table` (`id`, `col1`, `col2`, `date`) VALUES (NULL, '$val1', '$val2', '$date')";

Prepared statements

When working with prepared statements, consult the documentation to determine whether or not the statement's placeholders must be quoted. The most popular APIs available in PHP, PDO and MySQLi, expect unquoted placeholders, as do most prepared statement APIs in other languages:

// PDO example with named parameters, unquoted
$query = "INSERT INTO `table` (`id`, `col1`, `col2`, `date`) VALUES (:id, :col1, :col2, :date)";

// MySQLi example with ? parameters, unquoted
$query = "INSERT INTO `table` (`id`, `col1`, `col2`, `date`) VALUES (?, ?, ?, ?)";

Characters requring backtick quoting in identifiers:

According to MySQL documentation, you do not need to quote (backtick) identifiers using the following character set:

ASCII: [0-9,a-z,A-Z$_] (basic Latin letters, digits 0-9, dollar, underscore)

You can use characters beyond that set as table or column identifiers, including whitespace for example, but then you must quote (backtick) them.

Also, although numbers are valid characters for identifiers, identifiers cannot consist solely of numbers. If they do they must be wrapped in backticks.

JS quote best practices? ES6 / React -- single, double, backticks?

When working with JSX best practice is to use double quotes directly (no-braces) if just a simple string, or use backtick if interpolating a var into the string

JSX attempts to mimics HTML attributes making it more accessible when learning for first time, and beyond that I find it provides a clear visual distinction between JSX attributes and ordinary strings when scanning code, as they are likely syntax highlighted the same colour

In more general usage...

Backticks are ES6 introduction for template literals and should really only be used for that UNLESS you want to do a multiline string

There is no difference whatsoever between the single and double quotes, however in my experience there has been for a long time a move towards using single quotes (supported by linters) simply because it makes for less cluttered readable code

Sticking to a single code style across projects and enforcing via linting is also a good idea because it reduces escaping mistakes

It often depends on the other languages you have used as some languages allow interpolation in one or the other or in Java for example single quotes denote char rather than String

For what its worth here's my preference for the above reasons...

const awardWinningActor = 'Nic Cage'

const oscarNight = `And the award for Best Actor goes to ${awardWinningActor}`

const winnersSpeech = `Some really long but also totally awesome amazing speech
and also possibly some screaming and a leather jacket slung into the crowd`

<NicCage oscarFor="Best Actor" says={`Here's my ${winnersSpeech}`}} />


Related Topics



Leave a reply



Submit