|
27 | 27 | getCities().then(ret => cities.push(...ret)); |
28 | 28 |
|
29 | 29 | function findMatches(wordToMatch, cities) { |
| 30 | + if (wordToMatch === "") return []; |
30 | 31 | return cities.filter(place => { |
31 | 32 |
|
32 | 33 | const regex = new RegExp(wordToMatch, 'gi'); |
33 | 34 | return place.city.match(regex) || place.state.match(regex); |
34 | 35 | }) |
35 | 36 | } |
| 37 | + |
| 38 | + function numberWithCommas(x) { |
| 39 | + return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ','); |
| 40 | + } |
| 41 | + |
| 42 | + function displayMatches() { |
| 43 | + const matchArray = findMatches(this.value, cities); |
| 44 | + const html = matchArray.map(place => { |
| 45 | + const regex = new RegExp(this.value, 'gi'); |
| 46 | + const cityName = place.city.replace(regex, `<span class="hl">${this.value}</span>`); |
| 47 | + const stateyName = place.state.replace(regex, `<span class="hl">${this.value}</span>`); |
| 48 | + return ` |
| 49 | + <li> |
| 50 | + <span class="name">${cityName}, ${stateyName}</span> |
| 51 | + <span class="population">${numberWithCommas(place.population)}</span> |
| 52 | + </li> |
| 53 | + `; |
| 54 | + }).join(''); |
| 55 | + suggestions.innerHTML = html; |
| 56 | + |
| 57 | + |
| 58 | + } |
36 | 59 |
|
| 60 | + const searchInput = document.querySelector('.search'); |
| 61 | + const suggestions = document.querySelector('.suggestions'); |
| 62 | + |
| 63 | + searchInput.addEventListener('change', displayMatches); |
| 64 | + searchInput.addEventListener('keyup', displayMatches); |
| 65 | + |
37 | 66 |
|
38 | 67 |
|
39 | 68 | </script> |
|
0 commit comments