LoginSignup
18
14

More than 1 year has passed since last update.

Javascript のテンプレートリテラルって便利だよね

Last updated at Posted at 2018-06-04

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


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

出典

18
14
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
18
14