Visitar URL original
Completed type ahead challenge. City/State search functioning and dis… · wesbos/JavaScript30@714b7e0 · GitHub
Skip to content

Commit 714b7e0

Browse files
committed
Completed type ahead challenge. City/State search functioning and displaying correctly.
1 parent 5f11d11 commit 714b7e0

1 file changed

Lines changed: 40 additions & 0 deletions

File tree

‎06 - Type Ahead/index-START.html‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,46 @@
1717
<script>
1818
const endpoint = 'https://gist.githubusercontent.com/Miserlou/c5cd8364bf9b2420bb29/raw/2bf258763cdddd704f8ffd3ea9a3e81d25e2c6f6/cities.json';
1919

20+
21+
const cities = [];
22+
23+
fetch(endpoint)
24+
.then(blob => blob.json())
25+
.then(data => cities.push(...data))
26+
27+
function findMatches(wordToMatch, cities) {
28+
return cities.filter(place => {
29+
30+
const regex = new RegExp(wordToMatch, 'gi') // 'gi' = global, will search the whole string & insensitive to case
31+
return place.city.match(regex) || place.state.match(regex)
32+
});
33+
}
34+
35+
function numberWithCommas(x) {
36+
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
37+
}
38+
39+
function displayMatches() {
40+
const matchArray = findMatches(this.value, cities);
41+
const html = matchArray.map(place => {
42+
const regex = new RegExp(this.value, 'gi');
43+
const cityName = place.city.replace(regex, `<span class="h1">${this.value}</span>`);
44+
const stateName = place.state.replace(regex, `<span class="h1">${this.value}</span>`);
45+
return `
46+
<li>
47+
<span class="name">${cityName}, ${stateName}</span>
48+
<span class="population">${numberWithCommas(place.population)}</span>
49+
</li>
50+
`;
51+
}).join('');
52+
suggestions.innerHTML = html;
53+
}
54+
55+
const searchInput = document.querySelector('.search');
56+
const suggestions = document.querySelector('.suggestions');
57+
58+
searchInput.addEventListener('change', displayMatches);
59+
searchInput.addEventListener('keyup', displayMatches);
2060
</script>
2161
</body>
2262
</html>

0 commit comments

Comments
 (0)