String Interpolation in JavaScript

栏目: IT技术 · 发布时间: 4年前

内容简介:The string interpolation is the evaluation of a string literal containing placeholders that are replaced with corresponding values.In JavaScript, the template literals (strings wrapped in backticksLet’s see in more detail, with examples and best practices,

The string interpolation is the evaluation of a string literal containing placeholders that are replaced with corresponding values.

In JavaScript, the template literals (strings wrapped in backticks ` ) and ${expression} as placeholder implement the string interpolation:

const number = 42;
const message = `The number is ${number}`;

message; // => 'The number is 42'

Let’s see in more detail, with examples and best practices, how to use template strings to perform string interpolation in JavaScript.

Table of Contents

  • 1. The string literals
    • 2.1 Implicit to string conversion
  • 3. Escaping placeholders
    • 4.1 Refactor string concatentation
    • 4.3 Single quotes in placeholders
    • 4.4 Alternative solutions

1. The string literals

In JavaScript, there are 3 ways to create string literals.

First, which I prefer for plain strings, is to wrap the string into a pair of single quotes ' :

const message = 'Hello, World!';

The second, which I use rarely, is to wrap the string into a pair of double quotes " :

const message = "Hello, World";

The third, which permits string interpolation, is to wrap the string into a pair of backticks ` :

const message = `Hello, World!`;

The string literal wrapped in backticks ` is also named template string . This is the literal that supports the string interpolation.

2. The placeholders

The template string supports placeholders. The expression inside the placeholder is evaluated during runtime, and the result is inserted into the string.

The placeholder has a special format: ${expressionToEvaluate} . The expression inside the placeholder can be of any kind:

  • variables: ${myVar}
  • operators: ${n1 + n2} , ${cond ? 'val 1' : 'val 2'}
  • even function calls ${myFunc('argument')}

Here’s an example:

const greeting = 'Hello';
const who = 'World';

const message = `${greeting}, ${who}!`;message; // => 'Hello, World!'

${greeting}, ${who}!` is a template string having placeholders ${greeting} and ${who} .

On script execution, the first placeholder ${greeting} is replaced with the value of greeting variable, and the same for ${who} . The string interpolation result is 'Hello, World!' .

The sky is the limit for the expression you can put inside the placeholder. It can be an operator, a function call, or even more complex expressions:

const n1 = 2;
const n2 = 3;

const message1 = `The sum is ${n1 + n2}`;message1; // => 'The sum is 5';

function sum(num1, num2) {
  return num1 + num2;
}
const message2 = `The sum is ${sum(n1, n2)}`;message2; // => 'The sum is 5'

${n1 + n2} is a placeholder consisting of the addition operator and 2 operands. ${sum(n1, n2)} contains a function invocation.

2.1 Implicit to string conversion

The placeholder expression result is implicitly converted to a string.

For example, a number in a placeholder is transformed into a string:

const n = 3.5;
const message = `The number is ${n}`;

message; // => `The number is 3.5`

The expression n of the placeholder ${n} is evaluated to number 3.5 . The number 3.5 is then transformed into a string '3.5' , and inserted into the interpolation result: 'The number is 3.5' .

If the placeholder contains an object, following the conversion to string rule, the object is converted to a string too. The toString() method of the object is called to get the string representation of the object.

For example, let’s insert an array into a template string:

const numbers = [1, 2, 3];
const message = `The numbers are ${numbers}`;

message; // => 'The numbers are 1,2,3'

The placeholder ${numbers} contains an array of numbers.

toString() array method executes array.join(',') when the array is converted to string. Thus the string interpolation result is 'The numbers are 1,2,3' .

3. Escaping placeholders

Because the placeholder format ${expression} has a special meaning in the template literals, you cannot use the sequence of characters "${someCharacters}" without escaping.

For example, let’s try to create a string literal containing the sequence of characters ${abc} :

const message = `Some weird characters: ${abc}`;
// Throws "ReferenceError: abc is not defined"

Inserting ${abc} directly throws an error because JavaScript interprets ${abc} as a placeholder.

A backslash \ before the placeholder-like sequence of characters \${abc} solves the problem:

const message = `Some weird characters: \${abc}`;
message; // => 'Some weird characters follow: ${abc}'

In the template string Some weird characters: \${abc}` JavaScript interprets \${abc} as a sequence of characters, rather than a placeholder.

Alongside with ${abc} , the sequence of characters like ${abc and ${ also have to be escaped with a backslash \ :

const message = `Some weird characters: \${abc} \${abc \${`;

message; // => 'Some weird characters: ${abc} ${abc ${'

4. Best practices

4.1 Refactor string concatentation

The string interpolation should be used instead of string concatenation to construct lengthy strings.

If for some reason you’re still concatenating string literals and expressions using + operator:

const n1 = 2;
const n2 = 3;
const message = 'The sum of ' + n1 + ' and ' + n2 + ' is ' + (n1 + n2);
message; // => 'The sum of 2 and 3 is 5'

Then it’s the time to switch to string interpolation using template strings:

const n1 = 2;
const n2 = 3;
const message = `The sum of ${n1} and ${n2} is ${n1 + n2}`;
message; // => 'The sum of 2 and 3 is 5'

The template string usage requires less code and is easier to read.

4.2 Helper variables

When the template string contains many complex expressions, it might decrease the readability of the literal.

Here’s a template string having placeholders with complex expressions:

const n1 = 2;
const n2 = 3;

const message = 
  `Sum: ${n1 + n2}, difference: ${n1 - n2}, pow: ${Math.pow(n1, n2)}`;

message; // => 'Sum: 5, difference: -1, pow: 8'

The more complex the placeholders are, the more tempting is to add helper variables to store intermediate values.

const n1 = 2;
const n2 = 3;

const sum = n1 + n2;const diff = n1 - n2;const pow = Math.pow(n1, n2);
const message = `Sum: ${sum}, difference: ${diff}, pow: ${pow}`;

message; // => 'Sum: 5, difference: -1, pow: 8'

With the introduction of helper variables sum , diff and pow , the template string becomes lighter. Additionally, the code self-documents when the intermediate variables are used.

4.3 Single quotes in placeholders

I recommended using single quotes ' rather than backticks ` in the expressions inside the placeholder.

Let’s use the ternary operator. When the placeholder uses backticks ` it’s quite difficult to grasp the template string because there are too many backticks in the template string:

function getLoadingMessage(isLoading) {
  return `Data is ${isLoading: `loading...` : `done!`}`;}

But using single quotes inside the placeholder is easier to read:

function getLoadingMessage(isLoading) {
  return `Data is ${isLoading: 'loading...' : 'done!'}`;}

4.4 Alternative solutions

The string interpolation is helpful in many situations. But when the template string becomes large, with complex placeholder expressions, you might look for other solutions.

The following component constructors the CSS class based on many variables:

function LoadingMessage({ isLoading, isModal }) {
  const className = 
   `${isLoading ? 'loading' : ''} ${isModal ? 'modal' : ''}`;
  return (
    <div className={className}>
      {isLoading ? 'Loading...' : 'Done!'}
    </div>
  );
}

The template literal that determines the class name is difficult to understand. It has 2 ternary operators and a mix of string literals.

In this situation, I suggest avoiding the template strings in favor of the tool classnames . The tool constructs the class name string in a declarative and more expressive way.

Let’s refactor the component to use classnames :

import classNames from 'classnames';

function LoadingMessage({ isLoading, isModal }) {
  const className = classNames({    loading: isLoading,    modal: isModal  });
  return (
    <div className={className}>
      {isLoading ? 'Loading...' : 'Done!'}
    </div>
  );
}

This version of the component that uses the classnames tool is declarative and easy to understand.

If you’d need to add more CSS classes (for example to handle isErrorLoading ), the version that uses classnames grows without significantly affecting the readability.

5. Conclusion

The string interpolation is a great feature. It helps in inserting values into string literals in a concise and readable manner. And avoid the clumsy string concatenation approach.

In JavaScript, the template string implements the string interpolation.

A template string is defined by wrapping a sequence of characters into a pair of backticks I'm template string` . The template string placeholders have the format ${expression} , for example The number is ${number}` .

Don’t overcomplicate the string literal. If the template string uses complex expressions, try to introduce intermediate variables to store the expressions before putting them into placeholders.

As soon as you need a value inserted into a string literal, the template string is the way to go.


以上所述就是小编给大家介绍的《String Interpolation in JavaScript》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

马云:未来已来

马云:未来已来

阿里巴巴集团 / 红旗出版社 / 2017-4-1 / CNY 49.00

阿里巴巴集团:全球主要的互联网公司之一,由马云带领其他17个创始人,于1999年在中国杭州创立。阿里巴巴集团经营多元化的互联网业务,以“让天下没有难做的生意”为使命,致力于为创业者和消费者提供全球化的商业平台,打造开放、协同、繁荣的电子商务生态系统。自成立以来,阿里巴巴集团建立了领先的消费者电子商务、网上支付、B2B网上交易市场及云计算业务,并积极开拓无线应用、手机操作系统和互联网电视等领域。一起来看看 《马云:未来已来》 这本书的介绍吧!

URL 编码/解码
URL 编码/解码

URL 编码/解码

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具