태그드 템플릿 리터럴(Tagged Template Literal)

개발빼-엠·2023년 9월 8일

Javascript

목록 보기
10/10
post-thumbnail

태그드 템플릿 리터럴은 템플릿 리터럴이 발전된 형태로 템플릿 리터럴을 함수로 파싱할 수 있다.

// 템플릿 리터럴을 처리하는 태그드 템플릿 리터럴 함수
function taggedFunction(strings, ...args) {
  // 배열로 들어옴
  console.log(strings);
  console.log(args);

  return `${strings[0]} ${args[0]} ${strings[1]} ${args[1]}`
}

const arg1 = "food";
const arg2 = "animal";

// 태그드 템플릿 리터럴 함수 실행
// 템플릿 리터럴 안의 표현식(${})은 taggedFunction 함수의 args로
// 나머지 문자열은 strings이 되어 배열로 들어간다.
taggedFunction`I like${arg1}and${arg2}`

// taggedFunction 실행시
console.log(strings) -> ['I like', 'and', ''];
console.log(args) -> ['food', 'animal'];
return-> 'I like food and animal';

0개의 댓글