0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

テンプレートリテラル記法マスターまでの道のり

Posted at

テンプレートリテラル記法って何?

JSの中で分かりやすくHTML要素を書き込むためにあるものです。
書き方はバックティック文字(`)で囲みます。
これはめちゃくちゃ便利です。

改行はそのままでOK!

以下の例を見てください

var a = `ジャバ\nスク
リプト`;
console.log( a ); // ジャバ⏎スク⏎リプト

本来なら改行は\nで処理するはずでしたが、リテラル記法では
改行はそのまま改行すれば反映されます。
もちろん\nでもそのまま反映されます。

そのまま文字にしたい時

String.rawでそのまま文字にできます。
以下、例です

var a = String.raw`ジャバ\スク\nリプト`;
console.log( a ); // ジャバ\スク\nリプト

これだと\nの文字もそのまま書き込むことができます。

変数や計算式を入れるためには?

以下、例です。

var a = "Yes"
var b = `ジャバ${a}スク${111+222}リプト`;
console.log( b ); // ジャバYesスク333リプト

${}で囲めば大丈夫です。これもシンプルでいいですよね。

0
1
1

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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?