JS30 Day06_Ajax Type Ahead
요구사항
- 검색했을 때 새로고침 없이 검색결과가 입력한 글자마다 나오도록
- api에서 데이터를 가져오고, 가공해서 원하는 결과로 parsing
선수지식
- 정규표현식
- promise, fetch
- api call
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));
function findMatchs(wordToMatch, cities){
return cities.filter(place => {
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 displayMatchs(){
const matchArray = findMatchs(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.city.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', displayMatchs);
searchInput.addEventListener('keyup', displayMatchs);