이번 챌린지는 fetch API, 정규식 표현 등 아직 배우지 않은 것들이 나와서 당황스러웠다..
당장은 이해하기 어렵겠지만 딥다이브를 완독하고 나서 다시 한번 살펴봐야겠다!
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Type Ahead 👀</title>
<link rel="stylesheet" href="style.css" />
<link rel="icon" href="https://fav.farm/🔥" />
</head>
<body>
<form class="search-form">
<input type="text" class="search" placeholder="City or State" />
<ul class="suggestions">
<li>Filter for a city</li>
<li>or a state</li>
</ul>
</form>
<script>
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 findMatches(wordToMatch, cities) {
return cities.filter((place) => {
//검색어와 일치하는 city 또는 state 찾기
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);
</script>
</body>
</html>