JavaScript Template Literal


JavaScript 템플릿 리터럴(Template Literal)은 문자열을 다루는 더 간편하고 강력한 방법을 제공하는 문법입니다. 템플릿 리터럴은 백틱(backticks, `)으로 감싸여 있으며, 여러 줄 문자열, 문자열 내 표현식 삽입, 태그드 템플릿 등을 지원합니다.

1. 기본 문법

템플릿 리터럴은 백틱(`)으로 감싸서 사용합니다.

const name = "Alice";
const greeting = `Hello, ${name}!`;
console.log(greeting); // "Hello, Alice!"

2. 표현식 삽입

템플릿 리터럴은 ${expression} 구문을 사용하여 문자열 내부에 JavaScript 표현식을 삽입할 수 있습니다.

const a = 5;
const b = 10;
console.log(`The sum of ${a} and ${b} is ${a + b}.`); // "The sum of 5 and 10 is 15."

3. 여러 줄 문자열

템플릿 리터럴을 사용하면 여러 줄에 걸친 문자열을 쉽게 작성할 수 있습니다.

const multiLineString = `This is a string
that spans across
multiple lines.`;
console.log(multiLineString);

출력:

This is a string
that spans across
multiple lines.

4. 중첩 템플릿 리터럴

템플릿 리터럴 내부에서 또 다른 템플릿 리터럴을 사용할 수 있습니다.

const nested = `Outer ${`Inner ${`Nested`}`}`;
console.log(nested); // "Outer Inner Nested"

5. 태그드 템플릿 리터럴

태그드 템플릿 리터럴은 태그 함수와 함께 사용하여 템플릿 리터럴의 문자열과 표현식을 처리할 수 있습니다. 태그 함수는 템플릿 문자열 배열과 표현식 값들을 인수로 받습니다.

function tag(strings, ...values) {
  console.log(strings); // ["Hello, ", " world", "!"]
  console.log(values);  // ["beautiful"]
  return strings[0] + values[0] + strings[1] + strings[2];
}

const adjective = "beautiful";
const message = tag`Hello, ${adjective} world!`;
console.log(message); // "Hello, beautiful world!"

6. Raw 문자열

String.raw 태그 함수를 사용하면 이스케이프 처리를 하지 않은 “raw” 문자열을 얻을 수 있습니다.

const path = String.raw`C:\Development\profile\aboutme.html`;
console.log(path); // "C:\Development\profile\aboutme.html"

7. 템플릿 리터럴 사용 사례

7.1 HTML 생성

템플릿 리터럴은 HTML 문자열을 동적으로 생성하는 데 유용합니다.

const user = {
  name: "Alice",
  age: 30
};

const userProfile = `
  <div>
    <h1>${user.name}</h1>
    <p>Age: ${user.age}</p>
  </div>
`;
console.log(userProfile);

7.2 SQL 쿼리 생성

템플릿 리터럴은 SQL 쿼리를 동적으로 생성하는 데도 사용할 수 있습니다.

const table = "users";
const column = "name";
const value = "Alice";

const query = `SELECT * FROM ${table} WHERE ${column} = '${value}'`;
console.log(query); // "SELECT * FROM users WHERE name = 'Alice'"

7.3 로그 메시지 생성

템플릿 리터럴은 로그 메시지를 동적으로 생성하는 데도 유용합니다.

const level = "ERROR";
const message = "Something went wrong!";
const timestamp = new Date().toISOString();

const logMessage = `[${timestamp}] [${level}] ${message}`;
console.log(logMessage);

결론

템플릿 리터럴은 JavaScript에서 문자열을 다루는 더 간단하고 강력한 방법을 제공합니다. 표현식 삽입, 여러 줄 문자열, 태그드 템플릿 등을 통해 문자열 작업을 보다 직관적이고 유연하게 수행할 수 있습니다. 이를 통해 코드의 가독성을 높이고, 복잡한 문자열 생성 작업을 보다 쉽게 구현할 수 있습니다.


Leave a Reply

Your email address will not be published. Required fields are marked *