JavaScript 숫자 서식, URI 인코딩과 CSS 선택자 사용법

숫자를 화면에 표시하려면 toLocaleString(), URI 구성 요소 하나를 인코딩하려면 encodeURIComponent(), URL 쿼리를 조립하려면 URL.searchParams를 사용합니다. CSS와 querySelectorAll()은 같은 선택자 문법을 사용합니다. 예제에서 각 기능의 입력과 결과를 비교해 보세요.

표시할 숫자의 서식 정하기

로캘은 자릿수 묶음이나 소수점 같은 언어권의 표시 규칙입니다. en-US에서 123456789는 123,456,789, de-DE에서 1234.5는 1.234,5로 표시됩니다. 결과는 문자열입니다. 계산에는 원래 숫자를 쓰고, 서식 문자열의 구분 기호를 모든 로캘에서 같다고 가정하지 마세요. ECMA-402 Number.prototype.toLocaleString

console.log((123456789).toLocaleString("en-US"));
console.log((1234.5).toLocaleString("de-DE"));

전체 URI와 구성 요소 구분하기

URI(Uniform Resource Identifier)는 리소스를 식별합니다. encodeURI()는 전체 URI의 ?, &, # 같은 구조 문자를 보존합니다. encodeURIComponent()는 값 하나에 포함된 이런 문자도 인코딩합니다. 값의 &를 그대로 넘기면 매개변수 구분자로 해석될 수 있습니다. 디코딩할 때 decodeURI()는 예약 구분자를 유지하고 decodeURIComponent()는 인코딩된 구성 요소 하나를 복원합니다. ECMAScript URI Handling Functions

console.log(encodeURI("https://example.com/search?q=coffee&sort=new"));
console.log(encodeURIComponent("coffee&tea"));
console.log(decodeURIComponent("coffee%26tea"));

원래 값으로 쿼리 만들기

searchParams.set()에는 인코딩하기 전 값을 전달합니다. URLSearchParams는 문자열로 만들 때 공백을 +로, 값에 실제로 들어 있는 +는 %2B로 인코딩합니다. get()으로 값의 원문을 읽을 수 있습니다. coffee%26tea를 원래 값처럼 전달하면 %가 다시 인코딩되어 coffee%2526tea가 됩니다. WHATWG URLSearchParams

const url = new URL("https://example.com/search");
url.searchParams.set("q", "coffee & tea");
url.searchParams.set("page", "1");
console.log(url.href);
console.log(url.searchParams.get("q"));

디코딩 오류와 오래된 데이터 처리하기

잘못된 퍼센트 이스케이프 또는 유효하지 않은 UTF-8을 decodeURIComponent()에 전달하면 URIError가 발생할 수 있습니다. 예제 함수는 그 오류에만 null을 반환하고 다른 오류는 다시 발생시킵니다. 쿼리 문자열 전체를 디코딩한 뒤 나누기보다 매개변수 단위로 파싱하세요. 오래된 escape()의 %uXXXX는 별도 형식이므로 변경 전에 생성 방식을 확인합니다. ECMAScript URI Handling Functions

function decodeComponentSafely(text) {
  try {
    return decodeURIComponent(text);
  } catch (error) {
    if (error instanceof URIError) return null;
    throw error;
  }
}
console.log(decodeComponentSafely("%E0%A4%A"));

위치에 따라 자식 요소 선택하기

li:nth-child(2)는 두 번째 요소 자식이 li일 때만 일치합니다. li:nth-of-type(2)는 형제 li만 셉니다. 텍스트와 주석은 세지 않습니다. 여러 요소 유형을 섞어 비교하려면 div처럼 해당 요소들을 자식으로 둘 수 있는 컨테이너를 사용하세요. 이 선택자에 대한 selectivizr는 예전 Internet Explorer의 보완책이었습니다. W3C Selectors Level 4

#items > li:nth-child(2) {
  color: #a00000;
}
#items > li:last-child {
  font-weight: bold;
}

전체 HTML 예제 실행하기

아래 코드를 UTF-8로 javascript-notes.html에 저장하고 최신 브라우저에서 여세요. 실제 검색 요청 없이 주소를 표시합니다. coffee & tea를 입력하면 구성 요소에 %20과 %26이 표시되고, 쿼리 문자열은 공백에 +를 씁니다. 디코딩한 줄에는 원문이 나옵니다. CSS가 추가된 클래스에 스타일을 지정하므로 둘째 항목이 강조됩니다.

<!doctype html>
<html lang="ko">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>JavaScript 숫자 서식, URI 인코딩과 CSS 선택자 사용법</title>
  <style>
    .selected { color: #a00000; font-weight: bold; }
    #output { white-space: pre-wrap; overflow-wrap: anywhere; }
  </style>
</head>
<body>
  <label for="query">검색어</label>
  <input id="query" value="coffee &amp; tea">
  <button id="build" type="button">URL 만들기</button>
  <ul id="items"><li>첫째</li><li>둘째</li><li>셋째</li></ul>
  <pre id="output" aria-live="polite"></pre>
  <script>
    const input = document.getElementById("query");
    const output = document.getElementById("output");
    function show() {
      const value = input.value;
      const component = encodeURIComponent(value);
      const url = new URL("https://example.com/search");
      url.searchParams.set("q", value);
      output.textContent = [
        "구성 요소" + ": " + component,
        "디코딩" + ": " + decodeURIComponent(component),
        "검색 URL" + ": " + url.href,
        "서식이 적용된 숫자" + ": " + (123456789).toLocaleString("en-US")
      ].join("\n");
    }
    for (const item of document.querySelectorAll("#items > li:nth-child(2)")) {
      item.classList.add("selected");
    }
    document.getElementById("build").addEventListener("click", show);
    show();
  </script>
</body>
</html>