|
17 | 17 | <script> |
18 | 18 | const endpoint = 'https://gist.githubusercontent.com/Miserlou/c5cd8364bf9b2420bb29/raw/2bf258763cdddd704f8ffd3ea9a3e81d25e2c6f6/cities.json'; |
19 | 19 |
|
| 20 | +const cities = []; |
| 21 | + |
| 22 | +fetch(endpoint) |
| 23 | + .then(data => data.json()) |
| 24 | + .then(data => cities.push(...data)) |
| 25 | + |
| 26 | +function findMatch(word, cities){ |
| 27 | + return cities.filter(place => { |
| 28 | + const regex = new RegExp(word, 'gi'); //g - global, i = case insensitive |
| 29 | + return place.city.match(regex) || place.state.match(regex) |
| 30 | + }); |
| 31 | +} |
| 32 | +function numberWithCommas(x) { |
| 33 | + return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ','); |
| 34 | +} |
| 35 | + |
| 36 | +function displayItem(){ |
| 37 | + const matchArr = findMatch(this.value, cities); |
| 38 | + console.log(matchArr); |
| 39 | + const html = matchArr.map(place => { |
| 40 | + // const placeName = place.city; |
| 41 | + // const stateName = place.state; |
| 42 | + // const pop = place.population; |
| 43 | + |
| 44 | + const regex = new RegExp(this.value, 'gi'); |
| 45 | + const placeName = place.city.replace(regex, `<span class="hl">${this.value}</span>`); |
| 46 | + const stateName = place.state.replace(regex, `<span class="hl">${this.value}</span>`); |
| 47 | + |
| 48 | + return ` |
| 49 | + <li> |
| 50 | + <span>${placeName}, ${stateName} </span> |
| 51 | + <span> ${numberWithCommas(place.population)} </span> |
| 52 | + </li> |
| 53 | + ` |
| 54 | + }) |
| 55 | + |
| 56 | + return suggestions.innerHTML = html; |
| 57 | + |
| 58 | + |
| 59 | + |
| 60 | +} |
| 61 | + |
| 62 | +var searched = document.querySelector('.search'); |
| 63 | +searched.addEventListener('change', displayItem); |
| 64 | +searched.addEventListener('keyup', displayItem); |
| 65 | + |
| 66 | +var suggestions = document.querySelector('.suggestions'); |
| 67 | +// suggestions.innerHTML = something |
| 68 | + |
20 | 69 | </script> |
21 | 70 | </body> |
22 | 71 | </html> |
0 commit comments