CodeGym /행동 /Frontend SELF KO /Template Literals

Template Literals

Frontend SELF KO
레벨 37 , 레슨 2
사용 가능

3.1 중첩 표현식

템플릿 리터럴에서는 함수 호출, 삼항 연산자, 그리고 템플릿 리터럴 안에 또 다른 템플릿 리터럴 사용하는 등 어떤 표현식도 사용할 수 있어.

예시:

표현식 ${a + b}에서는 수학 연산이 이루어지고, 그 결과가 문자열 result에 삽입돼.

JavaScript
    
      const a = 5;
      const b = 10;

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

3.2 중첩 템플릿 리터럴

템플릿 리터럴은 중첩될 수 있어서 복잡한 문자열을 만들 수 있어.

예시:

객체 user의 메서드 greet()가 템플릿 리터럴 message 안에 중첩돼 있어.

JavaScript
    
      const user = {
        name: 'Bob',
        age: 25,
        greet() {
          return `Hello, ${this.name}!`;
        }
      };

      const message = `${user.greet()} You are ${user.age} years old.`;

      console.log(message); // "Hello, Bob! You are 25 years old."
    
  

3.3 태그된 템플릿 리터럴 (Tagged Templates)

태그된 템플릿 리터럴을 사용하면 템플릿 문자열을 처리하기 위해 함수를 호출할 수 있어. 이를 통해 국제화, 안전한 HTML 삽입 등의 추가적인 문자열 조작을 수행할 수 있어.

문법:

    
      function tag(strings, ...values) {
        // 문자열과 값 처리
        return 결과;
      }

      const result = tag`템플릿 스트링 안에 ${변수}`;
    
  

예시:

함수 highlight()는 문자열과 값을 처리하면서 값을 <span> 태그로 감싸서 highlight 클래스와 함께 반환해.

JavaScript
    
      function highlight(strings, ...values) {
        return strings.reduce((result, str, i) =>
          `${result}${str}${values[i] || ''}`, '');
      }

      const name = 'Carol';
      const hobby = 'painting';
      const message = highlight`My name is ${name} and I love ${hobby}.`;

      console.log(message);
      // "My name is <span class="highlight">Carol</span> and I love <span class="highlight">painting</span>."
    
  

3.4 안전한 값 삽입

템플릿 리터럴은 XSS (크로스 사이트 스크립팅) 같은 일반적인 보안 문제를 피하면서 값들을 안전하게 삽입하는 데 도움을 줘. 특히 사용자 데이터를 HTML에 삽입할 때 유용해.

예시:

함수 safeHTML()는 값 안의 위험한 문자를 교체해 XSS 공격을 방지해.

JavaScript
    
      function safeHTML(strings, ...values) {
        return strings.reduce((result, str, i) =>
          `${result}${str}${String(values[i]).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')}`, '');
      }

      const userInput = '<script>alert("XSS")</script>';
      const message = safeHTML`User input: ${userInput}`;

      console.log(message);
      // "User input: &lt;script&gt;alert("XSS")&lt;/script&gt;"
    
  
코멘트
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION