[ES6+] String / TIL # 10

velg·2021년 8월 11일

ES6+

목록 보기
3/6

ES6+의 String 관련 문법을 알아보자

Template literals

Template literals(템플릿 리터럴)은 백틱(``)을 사용하며 편리한 기능이 제공된다

Multi-line Strings

템플릿 리터럴은 \n도 받기 때문에 여러 줄의 문자열을 사용하고 싶을 때 효과적이다

const str = `
line 1
line 2
line 3
`;

// js로 html요소를 추가하는 예제
const wrapper = document.querySelector(".wrapper");

const sayHello = () => {
  const name = "정찬영";
  const div = `
        <div class="hello">
            <h1 class="title"> hello~ ${name}!</h1>
        </div>
    `;
  wrapper.innerHTML = div;
};

sayHello();


표현식 삽입법

문자열에 표현식을 삽입 할 때 템플릿 리터럴은 ${}을 통해 더욱 가독성있는 코드를 작성 할 수 있다

// 일반
const sayHello = (name = "정찬영") => console.log("hello " + name); // hello 정찬영 

// 템플릿 리터럴
const sayHi = (name = "정찬영") => console.log(`hi ${name}`); // hi 정찬영

Methods

ES6+에 추가된 쿨한 String 메서드를 알아보자

includes

문자열안에 해당 요소가 있는지 확인 후 참/거짓을 반환한다

const isEmail = (email) => email.includes("@");

console.log(isEmail(`poiuytasr@naver.com`)); // true

repeat

원하는 단어를 반복시켜준다

const password = "*".repeat(8);
console.log(password); // ********

startsWith / endsWith

시작 문자열과 끝 문자열을 판별해준다

const myEmail = "poiuytasr@naver.com";
console.log(myEmail.startsWith("p")); // true
console.log(myEmail.startsWith("poiuy")); // true
console.log(myEmail.endsWith("#com")); // false
console.log(myEmail.endsWith(".com")); // true

startsWith는 앞에서부터 주어진 문자열과 맞는지 검사 후 참/거짓을 반환하고 endsWith는 뒤에서부터 검사 후 참/거짓을 반환한다

tagged templete

템플릿 리터럴로 함수를 파싱 할 수 있다

파싱(parsing)?
구문 분석이라고도 하며, 문장의 구성 성분을 분해 분석하고 원하는 형태로 재조립하여 다시 빼내는 걸 말한다

const firstName = "정";
const lastName = "찬영";
const sayHello = (texts, firstName, lastName) => {
 console.log(`${texts[0]}${firstName}${lastName}`);
};
sayHello`hello ${firstName}${lastName}`; // hello 정찬영

함수의 첫 번째 인자는 문자열 값의 배열이고 나머지 인수는 표현식이다

끝! 🍣

profile
초보 개발자

0개의 댓글