개인노트 nomad ES6의 정석 #3 Strings

2023. 2. 2. 21:04개인노트-인강

# 3.0 Sexy Strings

 

## template literal

 

const add = (a, b) => a + b;

console.log(`hello how are you ${add(6, 7)}`);
// 출력
// hello how are you 13

 

# 3.1 HTML Fragments

 

string 안에 표현식을 넣을 수 있다는 점 말고도 template literal을 멋지게 사용할 수 있는 경우는 javascript 안에서 html을 쓸 수 있다는 점 입니다.

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

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

setTimeout(addWelcome, 2000);

 

# 3.2 HTML Fragments part Two

 

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

const friends = ["me", "lynn", "dal", "mark"];

const list = `
  <h1>People i love</h1>
  <ul>
    ${friends.map(friend => `<li>${friend}</li>`).join("")}
  </ul>
`;

wrapper.innerHTML = list;

 

# 3.3 Cloning Styled Components

 

## template literal 의 또 다른 활용.

const styled = (css) => console.log(css);

styled('border-radius: 10px; color:blue;');
// ' 를 사용하면 줄바꿈은 할 수 없습니다.

위 코드보다 좋게 바꾸면?

' 를 `로 바꾸면 줄바꿈 해도 문제 없음.

const styled = (css) => console.log(css);

styled(`border-radius: 10px; 
color:blue;`);

위 코드보다 좋게 바꾸면..?

()를 제거할 수 있습니다. styled() 와 styled``는 같은 동작을 합니다.

const styled = (css) => console.log(css);

styled`border-radius: 10px; 
color:blue;`;

styled`border-radius: 10px; 
color:blue;`; 

의 console.log의 결과는 아래와 같습니다.

console.log 결과 (엔터) 도 들어가있음.

매개변수에 배열이 들어가고 그 배열의 index 0 에 template literal로 입력한 string 값이 들어갑니다.

이것이 styled component에서 styled의 동작하는 방식이자, text로 function을 호출하는 또 다른 방법입니다.

const styled = aElement => {
  const el = document.createElement(aElement);
  return el;
};

const title = styled("h1");

console.log(title);
// 결과
// <h1></h1>

위 코드에 ``를 추가하면..

const styled = aElement => {
  const el = document.createElement(aElement);
  return el;
};

const title = styled("h1")`
  border-redius: 10px;
  color: blue;
`;

console.log(title);
// 에러
// Uncaught TypeError: styled(...) is not a function at app.js:6

이 에러의 의미는 function을 두번 호출했다는 의미입니다.

styled()에서 한 번 호출, styled() 뒤에 ``에서 또 한번 호출.

<h1></h1>에 이어서 ()함수를 호출하는 코드가 되어 버려서 에러가 발생합니다. 그럼 에러가 나지 않도록 하려면?

function안에서 function을 리턴하게 합니다.

const styled = aElement => {
  const el = document.createElement(aElement);
  return args => {
    console.log(args[0]);
  };
};

const title = styled("h1")`
  border-redius: 10px;
  color: blue;
`;

console.log(title);
// 결과
// border-radius: 10px; 
// color: blue;

console 부분을 element를 리턴하는 것으로 바꿔주면..

const styled = aElement => {
  const el = document.createElement(aElement);
  return args => {
    const styles = args[0];
    el.style = styles;
    return el;
  };
};

const title = styled("h1")`
  border-redius: 10px;
  color: blue;
`;

console.log(title);
// 결과
// <h1 style="border-radius: 10px; color: blue;"></h1>

 

물론 아래처럼 해도 괜찮습니다.

const title = styled("h1")(`
  border-redius: 10px;
  color: blue;
`);

 

조금 더 코드를 작성해 보면..

const styled = aElement => {
  const el = document.createElement(aElement);
  return args => {
    const styles = args[0];
    el.style = styles;
    return el;
  };
};

const title = styled("h1")`
  background-color: red;
  color: blue;
`;

const subtitle = styled("span")`
  color: green;
`;

title.innerText = "We just cloned";
subtitle.innerText = "Styled Components";

document.body.append(title, subtitle);

결과

 

# 3.4 More String Improvements!

 

## es6에서 처음 도입되고 도움이 많이 될 4가지의 string method

 

### Array.prototype.includes()

 

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/includes

includes() 메서드는 배열이 특정 요소를 포함하고 있는지 판별합니다.

 

### String.prototype.repeat()

 

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/String/repeat

repeat() 메서드는 문자열을 주어진 횟수만큼 반복해 붙인 새로운 문자열을 반환합니다.

 

### String.prototype.startsWith()

 

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith

startsWith() 메서드는 어떤 문자열이 특정 문자로 시작하는지 확인하여 결과를 true 혹은 false로 반환합니다.

 

### String.prototype.endsWith()

 

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith

The endsWith() 메서드를 사용하여 어떤 문자열에서 특정 문자열로 끝나는지를 확인할 수 있으며, 그 결과를 true 혹은 false로 반환한다.