0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

テンプレートリテラル

Last updated at Posted at 2025-03-15

これまでの学習で文字列や定数の連結には、「+」記号を用いてきました。

それ以外の方法として「テンプレートリテラル」という連結方法があります。
テンプレートリテラルを用いると、下のソースコードのように文字列の中に定数もしくは変数を埋め込むことができます。

qiita.js
const name="John";
console.log(`こんにちは、${name}さん`);
出力結果/コンソール
こんにちは、Johnさん

テンプレートリテラルの書き方

下の図のように、文字列の中で${定数} とすることで、文字列の中に定数や変数を含めることができます。
この時、下の図のように文字列全体をバッククォーテーション(`)で囲む必要があります。

image.png


また、下のソースコードのように複数の定数や変数を埋め込むこともできます。

qiita.js
const name="John";
const age=20;
console.log(`${name}${age}歳です`);
出力結果/コンソール
Johnは20歳です

例題

テンプレートリテラルを用いて、以下の例題に取り組んでみましょう。

qiita.js
const name = "John";
const age = 20;

// 「ぼくの名前は〇〇です」とコンソールに出力してください
console.log("ぼくの名前は" + name + "です");

// 「今は〇〇歳です」と出力してください
console.log("今は" + age + "歳です");

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?