본문 바로가기
공부/javascript

2022.07.13 - javascript 30 [ day6 ] type ahead

by 기묜몬 2022. 7. 13.

- 도시 api 를 이용하여 키워드를 통해 도시 이름을 검색할 수 있는 페이지를 만들었다. 

나중에 한국 공공 api 를 이용해서 충북 맛집리스트 키워드 검색 등 만들어보고 싶은 것이 많아졌다 ! 아자 아자 

[ JS ]

const endpoint =
        "https://gist.githubusercontent.com/Miserlou/c5cd8364bf9b2420bb29/raw/2bf258763cdddd704f8ffd3ea9a3e81d25e2c6f6/cities.json";
      const cities = []; // 빈배열

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

      // Blob을 활용하면 자바스크립트로 이미지, 음성,영상 등의 이진 데이터를 다룰 수 있습니다.
      // 또한 Blob을 상속받는 file 객체로 로컬 파일을 다룰 수 있게 됩니다

      function findMatches(wordToMatch, cities) {
        return cities.filter((place) => {
          // city or state matches what was searched
          // 입력값 단어와 조금이라도 일치하는 도시들의 배열을 반환한다.
          const regex = new RegExp(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 = 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;
      }
      const searchInput = document.querySelector(".search");
      const suggestions = document.querySelector(".suggestions");
      searchInput.addEventListener("change", displayMatches);
      searchInput.addEventListener("keyup", displayMatches);

[ 분석 ]

1. endpoint 상수에 도시 api주소를 저장한 후 cities 빈 배열을 선언한다. 

  const endpoint =
        "https://gist.githubusercontent.com/Miserlou/c5cd8364bf9b2420bb29/raw/2bf258763cdddd704f8ffd3ea9a3e81d25e2c6f6/cities.json";
      const cities = []; // 빈배열

 

2. fetch 함수를 통해서 response를 얻어내고, 그 값을 json 변환하고, json 변환된 data를 cities배열에 push 한다.

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

console.log(cities)를 하면 cities에 도시정보가 담겨있는 것을 확인할 수 있음

 

 

3. 입력된 키워드와 일치하는 도시들의 배열을 반환

function findMatches(wordToMatch, cities) {
        return cities.filter((place) => {
          // city or state matches what was searched
          // 입력값 단어와 조금이라도 일치하는 도시들의 배열을 반환한다.
          const regex = new RegExp(wordToMatch, "gi");
          return place.city.match(regex) || place.state.match(regex);
        });
      }

 

4. 입력된 키워드와 일치하는 도시들의 배열을 matchArray에 저장하고, map()메서드를 활용하여 matchArray를 돌면서 새로운 배열을 만든다. join()메서드를 통해 모든 요소를 하나의 문자열로 만들고,  suggestion의 innerHTML에 넣어준다. 

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

 

5. html 클래스를 가져와 addEventListener를 통해 이벤트를 설정해준다.

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

 

 

[ 배운 것 ] 

RegExp : 패턴을 사용해 텍스트를 판별할 때 사용한다. 

텍스트를 검색하거나 치환하거나 어떠한 문자열을 추출하고자 할때 쓰인다. 메타문자(특수한 문자/기호)를 이용하여 이루어진 패턴 

* 사용 예제

개별 숫자 - /[0-9]/g
-> 전체에서  0~9사이에 아무 숫자 '하나'  찾음 
개발 문자 - /[to]/g
-> 전체에서 t  혹은 o  를 모두 찾음