LoginSignup
0
0

More than 1 year has passed since last update.

[JavaScript] 文字列中での変数展開(テンプレートリテラル)

Last updated at Posted at 2021-12-08

JavaScriptにおいて、文字列中に変数や式を埋め込むことができるテンプレートリテラルについてまとめておく。これは、+を用いて文字列を連結させる方法より、簡潔に書くことができる。

書き方

テンプレートリテラルを使用して、変数や式を埋め込む書き方のポイントは以下の2点である。
① 文字列を「`(バッククォート)」で囲む。
② 文字列に埋め込む変数や式をプレースホルダ${}で囲む。
①は「'(シングルクォート)」ではないことに注意。

実装例

const price = 120;
const number = 3;

// + を使用した場合
const plus = "単価は、" + price + "です。" + number + "個買うと合計" + price * number + "円です。";
console.log(plus);    // 単価は、120です。3個買うと合計360円です。

// テンプレートリテラルを使用した場合
const template = `単価は、${price}です。${number}個買うと合計${price * number}円です。`
console.log(template);    // 単価は、120です。3個買うと合計360円です。

まとめ

今回は変数展開を中心にテンプレートリテラルをまとめてみた。
このテンプレートリテラルは他にも以下の2点の特徴がある。
① 改行コードを記述しなくても、コード上の改行が反映される。
② 「\(バックスラッシュ)」でエスケープ処理ができる。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0