Help us understand the problem. What is going on with this article?

Javascript のテンプレートリテラルって便利だよね(oゝД・)bーー

More than 1 year has passed since last update.

javascriptのテンプレートリテラル

Template literal は組み込み式を扱うことができる文字列リテラルです。複数行文字列や文字列内挿機能を使用できます。ES2015 / ES6 仕様の以前のエディションでは、"template strings" と呼ばれていました。

テンプレートリテラルを使うと、文字列の扱いが便利になります。


基本的な文法

console.log(`文字列`) // " ` "で囲む

" ' との違い

改行

before

console.log("1行目\n2行目")

after

console.log(`1行目
2行目`)

index.png


文字列の結合

before

const str = "num";
const num = 123;

console.log(str + " = " + num);
console.log("1 + 2 = " + (1 + 2) + " です。");

after

const str = "num";
const num = 123;

console.log(`${str} = ${num}`);
console.log(`1 + 2 = ${1 + 2} です。`);

index.png


エスケープ処理

before

console.log("エスケープ\\nされています");

after

console.log(String.raw`エスケープ\nされています`);

index.png


他にも使い方はありますが、とりあえずこの辺で。

出典

lemon2003
The Coder (雑魚ーダー) フロントエンドメイン Qrunch: https://lemon2003.qrunch.io/
https://resume.id/lemon2003
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした