Javascript의 template literal

singleheart·2024년 2월 22일
0

요즘 자바스크립트를 배우고 있다. 옛날에 배웠더니 ES6에서 추가된 문법에 대해서는 전혀 모르고 있었다. 파이썬을 먼저 익히고 왔더니 자바스크립트도 파이썬과 마찬가지로 '"로 문자열을 나타내는 것은 같은데, `으로 문자열을 나타내는 새로운 문법이 있었다.

자바스크립트의 template literal은 문자열을 ` (backtick)으로 감싸는데, 파이썬의 """f를 합친 것 같은 역할이다. 즉,

  1. multiline 문자열을 나타낼 수 있다
  2. ${}으로 변수나 표현식을 포함할 수 있다. {}뿐만 아니라 앞에 $를 붙여야한다는 점이 파이썬과 다르다

여기에 파이썬과 다른 특징이 있는데, nested template literal이라고 해서 ${} 안에 또 다시 ` 문자열을 넣을 수 있다. 즉, `a${`b`}c`'abc'와 같다.

tagged templates이라고 template literal을 파싱하는 함수(tag function)를 만들어서 적용할 수도 있다.

아래는 모질라 사이트에서 가져온 예시이다:

const person = "Mike";
const age = 28;

function myTag(strings, personExp, ageExp) {
  const str0 = strings[0]; // "That "
  const str1 = strings[1]; // " is a "
  const str2 = strings[2]; // "."

  const ageStr = ageExp < 100 ? "youngster" : "centenarian";

  // We can even return a string built using a template literal
  return `${str0}${personExp}${str1}${ageStr}${str2}`;
}

const output = myTag`That ${person} is a ${age}.`;

console.log(output);
// That Mike is a youngster.
profile
개발자

0개의 댓글