Visitar URL original
challenge 6 is completed. Find cities. · wesbos/JavaScript30@13d32fb · GitHub
Skip to content

Commit 13d32fb

Browse files
committed
challenge 6 is completed. Find cities.
1 parent 206505a commit 13d32fb

1 file changed

Lines changed: 41 additions & 0 deletions

File tree

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

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

20+
const cities = [];
21+
22+
fetch(endpoint)
23+
.then(blob => blob.json())
24+
.then(data => cities.push(...data));
25+
26+
function findMatches(wordToMatch, cities) {
27+
return cities.filter(place => {
28+
const regex = new RegExp(wordToMatch, 'gi');
29+
return place.city.match(regex) || place.state.match(regex);
30+
});
31+
}
32+
33+
function numberWithComas(x) {
34+
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
35+
}
36+
37+
function displayMatches() {
38+
const matchArray = findMatches(this.value, cities);
39+
const regex = new RegExp(this.value, 'gi');
40+
41+
const html = matchArray.map(place => {
42+
const cityName = place.city.replace(regex, `<span class="hl">${this.value}</span>`);
43+
const stateName = place.state.replace(regex, `<span class="hl">${this.value}</span>`);
44+
return `
45+
<li>
46+
<span class="name">${cityName}, ${stateName}</span>
47+
<span class="population">${numberWithComas(place.population)}</span>
48+
</li>
49+
`;
50+
}).join('');
51+
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);
60+
2061
</script>
2162
</body>
2263
</html>

0 commit comments

Comments
 (0)