[JS] Template literals란?

[JS] Template literals란?

  • ES6에서  Template literals가 등장
  • 사용 방법
    • ``안에 문자열을 그대로 쓰고 변수(혹은 함수)를 사용할 때는 ${변수명/함수}으로 사용하면 됨
var obj = {a:1, b:2};
console.log('In the obj object, there are properties. a is '+obj.a+' and b is '+obj.b+'.');
// In the obj object, there are properties. a is 1 and b is 2.
  • 위의 예제에서는 변수 obj안에 객체를 담았음
  • console.log메서드를 호출할 때 문자열은 ''안에 표현하고, 문자열고 변수를 합칠때는 +를 사용함
  • 이 방식은 문자열에 들어와야하는 변수가 많아지면 복잡해지고 띄오쓰기 등 혼란이 일어남
    • 따라서 등장한 것이 Template literals
var obj = {a:1, b:2};
console.log(`In the obj object, there are properties. a is ${obj.a} and b is ${obj.b}.`);
// In the obj object, there are properties. a is 1 and b is 2.

  • 위의 예제는 Template literals를 사용한 것


`string text`

`string text line 1
 string text line 2`

`string text ${expression} string text`

tag `string text ${expression} string text`

  • 이렇게 사용하면 됨
  • 줄 바꿈도 가능함, 기존 자바스크립트는 \n을 사용했어야함
console.log("string text line 1\n"+
"string text line 2");
// "string text line 1
// string text line 2"


console.log(`string text line 1
string text line 2`);
// "string text line 1
// string text line 2"

댓글

이 블로그의 인기 게시물

[Python] # -*- coding: utf-8 -*-를 쓰는 이유

[소프트웨어공학] NS(Nassi-Schneiderman) 차트

[컴퓨터네트워크] Telnet이란?