JavaScript

[ JS ] Strings

Design-loving front-end engineer 2022. 7. 5. 10:27

๐Ÿ”ด  Using BackQuote

โšช  ` `๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ๋ฌธ์ž์—ด๊ณผ ๋ณ€์ˆ˜๋ฅผ + ์—ฐ์‚ฐ์ž ์—†์ด ํ‘œํ˜„ํ•  ์ˆ˜ ์žˆ๋‹ค.

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

console.log(`hello how are you ${add(6, 6)}`);

 

๐ŸŸ   HTML Fragments

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

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

const friends = ["me", "lin", "hyun", "hun"];

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

wrapper.innerHTML = list;

 

๐ŸŸก  Cloning Styled Components

๋ฆฌ์•กํŠธ์˜ Styled Components์™€ ๋น„์Šทํ•œ ๋ฐฉ์‹์œผ๋กœ ๋ฐ”๋‹๋ผ ์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ์—์„œ HTML ์š”์†Œ๋ฅผ ์ถ”๊ฐ€ํ•˜๊ณ , CSS๋ฅผ ์ ์šฉํ•  ์ˆ˜ ์žˆ๋Š” ๋ฐฉ๋ฒ•์„ ์•Œ์•„๋ณด๋„๋ก ํ•˜์ž.

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

 

๐ŸŸข  Useful String Functions!

โšช  includes

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

console.log(isEmail("ryong@gmail.com"));  // true

โšช  repeat

 
const CC_NUMBER = "6060";

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

console.log(displayName);  // **********6060

โšช  startsWith && endsWith

 
const name = "Mr. Ryong";

console.log(name.startsWith("Mr");  // true
console.log(name.endsWith("Ryong");  // true

โšช  padStart && padEnd

 
"5".padStart(5, "x");
// xxxxx5

"5".padEnd(5, "x");
// 5xxxx

let hours = 8;
let minutes = 7;
let seconds = 28;

console.log(`${hours.padStart(2, "0").padEnd(3, "h")}:
             ${minutes.padStart(2, "0").padEnd(3, "m")}:
             ${seconds.padStart(2, "0").padEnd(3, "s")}`);
// 08h:07m:28s

โšช  trim, trimStart, trimEnd

โšช  form ์ž…๋ ฅ์„ ๋ฐ›์€ ๋ฐ์ดํ„ฐ๋ฅผ ์ฒ˜๋ฆฌํ•  ๋•Œ ์œ ์šฉํ•˜๋‹ค.

 
let name = "     jeong seung   ryong     ";

name.trimStart();
// "jeong seung   ryong     "

name.trimEnd();
// "     jeong seung   ryong"

name.trim();
// "jeong seung   ryong"