const html = matchArray.map(v => {
const regex = new RegExp(searchInput.value, 'gi');
const cityName = v.city.replace(regex, `<span class="hl">${searchInput.value}</span>`);
const stateName = v.state.replace(regex, `<span class="hl">${searchInput.value}</span>`);
return `
<li>
<span>${cityName}, ${stateName}</span>
<span class="population">${Number(v.population).toLocaleString()}</span>
</li>
`
}).join("")
const endpoint = 'https://gist.githubusercontent.com/Miserlou/c5cd8364bf9b2420bb29/raw/2bf258763cdddd704f8ffd3ea9a3e81d25e2c6f6/cities.json';
const cities = [];
fetch(endpoint)
.then(res => res.json())
.then(data => cities.push(...data));
const searchInput = document.querySelector('.search');
const suggestions = document.querySelector('.suggestions');
const findMatches = () => {
const regex = new RegExp(searchInput.value, 'gi');
return cities.filter(v => {
return v.city.match(regex) || v.state.match(regex)
})
}
function addSearchList() {
const matchArray = findMatches();
const html = matchArray.map(v => {
const regex = new RegExp(searchInput.value, 'gi');
const cityName = v.city.replace(regex, `<span class="hl">${searchInput.value}</span>`);
const stateName = v.state.replace(regex, `<span class="hl">${searchInput.value}</span>`);
return `
<li>
<span>${cityName}, ${stateName}</span>
<span class="population">${Number(v.population).toLocaleString()}</span>
</li>
`
}).join("")
suggestions.innerHTML = html;
}
searchInput.addEventListener('change', addSearchList);
searchInput.addEventListener('keyup', addSearchList);
강의보고 나면 별로 안 어려운데 처음에 혼자 구현하려면 왤케 머리가 안 돌아가는지 모르겠다...
findMatches함수에서 filter쓸 때도 정규표현식이랑 match는 생각도 못하고 includes로 하려다가 대소문자 처리 때문에 뻘 짓하고.. 많이 배운다 🥲