본문 바로가기
챌린지/JavaScript 30일 챌린지

[JavaScript 30일 챌린지] : 6일차

by 오주현 2022. 2. 2.
반응형

constendpoint= '<<a href=https://gist.githubusercontent.com/Miserlou/c5cd8364bf9b2420bb29/raw/2bf258763cdddd704f8ffd3ea9a3e81d25e2c6f6/cities.json>https://gist.githubusercontent.com/Miserlou/c5cd8364bf9b2420bb29/raw/2bf258763cdddd704f8ffd3ea9a3e81d25e2c6f6/cities.json</a>>';

constcities= [];
fetch(endpoint)
  .then(blob => blob.json())
  .then(data =>cities.push(...data));

function findMatches(wordToMatch, cities) {
  return cities.filter(place => {
    const regex = newRegExp(wordToMatch, 'gi');
    return place.city.match(regex) || place.state.match(regex)
  });
}

function numberWithCommas(x) {
  return x.toString().replace(/\\B(>=(\\d{3})+(?!\\d))/g, ',');
}

function displayMatches() {
  const matchArray = findMatches(this.value,cities);
  const html = matchArray.map(place => {
    const regex = newRegExp(this.value, 'gi');
    const cityName = place.city.replace(regex, `<span class="hl">${this.value}</span>`);
    const stateName = place.state.replace(regex, `<span class="hl">${this.value}</span>`);
    return `
      <li>
        <span class="name">${cityName}, ${stateName}</span>
        <span class="population">${numberWithCommas(place.population)}</span>
      </li>
    `;
  }).join('');
suggestions.innerHTML = html;
}

constsearchInput=document.querySelector('.search');
constsuggestions=document.querySelector('.suggestions');

searchInput.addEventListener('change', displayMatches);
searchInput.addEventListener('keyup', displayMatches);

JSON 형식의 데이터를 가져와서 검색할 수 있는 JS를 작성했다.

검색 창이 떠있고

JSON에 있는 도시를 검색하면 연관 결과가 나오게 된다.

반응형

댓글