티스토리 뷰

live search 기능을 구현하는 파트입니다.

 

start 파일을 보면 endpoint라는 변수안에 url만 들어있습니다.

이 url로 들어가보시면 데이터들이 들어있는것을 볼 수 있습니다.

 

우선 여기서는 fetch를 이용해서 데이터를 가져와 cities라는 변수에 넣겠습니다

const cities = [];

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

 

그리고 입력한 단어가 cities안에 있는지 비교해서 찾는 findMatches라는 함수를 작성해보겠습니다.

function findMatches(wordToMatch, cities) {
  return cities.filter(place => {
    const regex = new RegExp(wordToMatch, 'gi'); // 문자열 전체판별, 대소문자 무시.
    return place.city.match(regex) || place.state.match(regex); // state와 place에서 비교
  });
}

 

다음으로 일치하는 결과를 보여주는 displayMatches 함수를 작성해보겠습니다.

function displayMatches() {
  const matchArray = findMatches(this.value, cities);
  const html = matchArray.map(place => {
    const regex = new RegExp(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;
}

코드를 설명하자면 먼저 작성해둔 findMatches를 호출하여 일치하는 값을 matchArray에 값을 담습니다.

matchArray의 값을 map 메소드를 이용하여 새로운 배열로 생성하고 텍스트로 합쳐(join) 만듭니다.

 

map 메소드 안에서는 정규표현식 객체를 만듭니다.

cityName과 stateName 변수는 입력된 텍스트의 앞뒤로 span 태그를 붙입니다.

이 부분으로 highlighting을 합니다.

 

numberWithCommas 함수는 인구수를 보기 편하게 만들기 위한 함수입니다.

이 함수는 아래와 같이 작성합니다.

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

 

이제 serchInput element에 키이벤트를 걸어야 하기에 아래의 코드를 추가합니다.

const searchInput = document.querySelector('.search');
const suggestions = document.querySelector('.suggestions');
searchInput.addEventListener('keyup', displayMatches);

 

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/05   »
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 29 30 31
글 보관함