Tempalte Literals
템플릿 리터럴은 ES6 JavsScript 문법이다. 일반 문자열과 달리 백틱(`) 문자를 사용하며 런타임 시점에서 문자열로 처리, 변환된다.
일반적인 문자열에서 줄바꿈
// 중간에 줄바꿈 시 오류 발생!
var name = "mint";
var text = "Hello, " + name + "
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.";
var name = "mint";
var text = "Hello, " + name + "\n\
\
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.";
일반 문자열에서 줄바꿈은 오류를 발생시키기 때문에 역슬래시n {\n)를 사용해야한다.
템플릿 리터럴 문자열 줄바꿈
var template = `
Hello, ${name}
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
`;
console.log(template);
템플릿 리터럴은 따옴표 대신 백틱(`)문자로 감싸준다.
여러 줄에 걸쳐 문자열 작성 가능하며 템플릿 리터럴 내부의 white-space는 그대로 적용되기 때문에 따로 줄바꿈 이스케이프 시퀀스를 사용할 필요가 없다.
템플릿 리터럴의 표현식 삽입
표현식 : ${ }
+연산자
를 사용하지 않고 문자열 인터폴레이션으로 문자열 삽입이 가능하다.
일반 문자열에서 +name
으로 사용했다면, 템플릿 리터럴은 ${name}
으로 표현한다.
var fruits = "사과";
console.log("나는 " + fruits + "를 좋아한다.");
console.log(`나는 ${fruits}를 좋아한다.`);
${ }
표현식이 훨씬 가독성이 좋고 사용이 간편하다.
댓글