ES6 스터디 정리 : STRINGS

Llux lux·2022년 4월 9일
0

ES6 스터디

목록 보기
3/21

3.1 string 출력하기

string 을 조합하기 위해 그동안 + 를 많이 사용하였다.

const sayHi = (aName) => "Hello " + aName + ", Nice to meet you!";

이제 백틱(``) 을 사용해서 탬플릿화 된 방식을 사용하자
문자열 식별이 더 간결하고 변수 또는 함수를 바로 사용 할 수 있다.

const sayHi = (aName) => `Hello ${aName}, Nice to meet you!`;
//${} 내에 변수를 사용하여 문자열을 생성할 수 있다.
const a = 10;
const b = 20;
console.log(`${a} + ${b} 결과는 ${() = a + b} 입니다.`);
//${} 내에 변수 외에 arrow function 을 사용할 수 있다.
const add = (a, b) => a + b;
console.log(`${a} + ${b} 결과는 ${add(10, 20)} 입니다.`);
//${} 내에 함수를 호출 할 수도 있다.

3.2 HTML Fragments

const wrapper = document.querySelector(".wrapper");
const addWelcome = () => {
    const div = document.createElement("div");
    const h1 = document.createElement("h1");
    h1.innerText = "Hello";
    div.append(h1);
    wrapper.append(div);
}
setTimeout(addWelcome, 2000);
//직접 HTML 영역을 만드려면 이렇게 복잡해진다. 요소가 추가되면 방대한 코드가 될것이다.

아래와 같이 template leteral string 으로 사용해보자
더욱 가독성이 좋아진다.

const wrapper = document.querySelector(".wrapper");
const addWelcome = () => {
    const div = `
        <div class="hello">
            <h1 class="title">Hello</h1>
        </div>
    `;
    wrapper.innerHTML = div;
}

3.3 HTML Fragments2

const wrapper = document.querySelector(".wrapper");

const friends = ["me" ,"lynn", "dal", "mark"];
const ul = document.createElement("ul");
friends.forEach(friend => {
    const li = document.createElement("li");
    li.innerHTML = friend;
    ul.append(li);
});
wrapper.append(ul);
//데이터를 사용 할 때 직접 html 요소를 생성하면 복잡해진다.
const wrapper = document.querySelector(".wrapper");

const friends = ["me" ,"lynn", "dal", "mark"];
const list = `
    <h1>Friend List</h1>
    <ul>
        ${friends.map(friend => `<li>${friend}</li>`).join("")}
    </ul>
`;
wrapper.innerHTML = list;
//`` 을 사용해 가독성이 좋으며 데이터도 적용하기 쉽다.

3.4 styled Components 클론해보기

const styled = aElement => {
    const el = document.createElement(aElement);
    //styled 호출뒤에 추가가된 string 이 args 로 전달 되었다.
    return args => {
        const styles = args[0];
        el.style = styles;
        return el
    }
}

const title = styled("h1")`
border-radius:10px;
color:blue;
`;
const subTitle = styled("h4")`
border-radius:10px;
color:red;
`;
//styled 라는 함수 호출 후 바로 뒤에 template literal string 으로 string 을 args 로 전달한다.

title.innerText = "This is title";
subTitle.innerText = "This is subTitle";

document.body.append(title, subTitle);

3.5 유요한 string 함수 알아보기

1. includes

문자열에 조회하려는 문자가 포함되어 있는지 검사하여 boolean 을 리턴한다.

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

console.log(isEmail("gildong@gmail.com"));
//indexOf 보다는 includes 를 사용하자.

2. repeat

특정문자열을 원하는 횟수만큼 반복시켜준다.

const CC_NUMBER = "6060";

const displayName = `${"*".repeat(10)}${CC_NUMBER}`;
console.log(displayName);
//**********6060

3. startWith, endsWith

문자의 시작과 끝에 특정 문자로 끝나는지 검사를 수행하여 boolean 을 리턴한다.

const userName = "Hong gildong";

console.log(userName.startsWith("H")); //true
console.log(userName.endsWith("n")); //false
profile
하하하

0개의 댓글