LoginSignup
3
1

More than 1 year has passed since last update.

【JavaScript】文字列への変数の埋め込み

Posted at

「`」(バッククォート)を使うと、簡単に文字列に変数を埋め込むことができる。
「`」で括った文字列の中に、${[変数名]}の形で変数名を書けばよい。
クラスのメンバ、数式なども指定することが可能。改行もそのまま反映される。

sample
class myClass{
  constructor(argName, argAge, argHeight){
    this.name = argName;
    this.age = argAge;
    this.height = argHeight;
  }
}

var hello = 'こんにちは';
var person = new myClass('penguin', 7, 62);

console.log(`「${hello}!」`);
console.log(`「私は、${person.name}${person.age})です」`); // クラスのメンバ
console.log(`「大きさは${person.height/100}mです」`); // 数式
console.log(`「アジは大好きですが、
サバは苦手です」`); // 改行

// 出力結果▽
//「こんにちは!」
//「私は、penguin(7)です」
//「大きさは0.62mです」
//「アジは大好きですが、
// サバは苦手です」

今まで"「私は、" +name+ "(" +age+ ")です」"のように+での結合を使っていた部分がだいぶスマートになる。

3
1
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
3
1