[JS] ES6 - Strings

[JS] ES6 - Strings

이채현

Strings

Template Literal

variable을 가진 문자열을 쓰는 방법에 대한 개선

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
const sayHi = (aName = "anon") => {
return "Hello " + aName;
};

==>
/**
* 변수
*/
const sayHi = (aName = "anon") => {
return `Hello ${aName}`;
}
/**
* 함수
*/
const add = (a, b) => a + b;
console.log(`hello how are you ${add(6, 6)}`);

HTML Fragments 1

1
2
3
4
5
6
7
8
9
10
11
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, 1000);

1
2
3
4
5
6
7
8
const addWelcome = () => {
const div = `
<div class="hello">
<h1>Hello</h1>
</div>
`;
wrapper.innerHTML = div;
};
  • template literal은 ``` … space를 고려한다.

HTML Fragments 2

1
2
3
4
5
6
7
8
9
10
const alphas = ["A", "B", "C", "D"];

const ul = document.createElement("ul");
const list = `
<h1>Alphabet</h1>
<ul>
${alphas.map(alpha => `<li>${alpha}</li>`).join("")}
</ul>
`;
wrapper.innerHTML = list;

Cloning Styled Components

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/**
* Cloning Styled Components
*/

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);

More String Improvements

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/**
* includes()
*/
const isEmail = (email) => email.includes("@");
console.log(isEmail("[email protected]")); // true
console.log(isEmail("myEmail")); // false

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

/**
* startsWith(), endsWith()
*/
const name = "Mr. abc";
console.log(name.startsWith("Mr")); // true
console.log(name.endsWith("abc")); // true
Author

Chaehyeon Lee

Posted on

2022-01-01

Updated on

2022-06-26

Licensed under

댓글