|
24 | 24 | }) |
25 | 25 | .then((data) => { |
26 | 26 | cities.push(...data); |
27 | | - |
28 | | - console.log(findMatches('san', cities)); |
29 | 27 | }) |
30 | 28 | .catch((e) => { |
31 | 29 | console.log(e); |
32 | 30 | }) |
33 | 31 |
|
34 | | - function findMatches(wordToMatch, cities){ |
35 | | - return cities.filter((place) => { |
| 32 | +function findMatches(wordToMatch, cities){ |
| 33 | + return cities.filter((place) => { |
| 34 | + |
| 35 | + // g means we will do a global search via the regex and i means case incensitive |
| 36 | + const regex = new RegExp(wordToMatch, 'gi'); |
| 37 | + return place.city.match(regex) || place.state.match(regex); |
| 38 | + }); |
| 39 | +} |
| 40 | + |
| 41 | + |
| 42 | +function displayMatches(){ |
| 43 | + const matchArray = findMatches(this.value, cities); |
| 44 | + |
| 45 | + // .join turns array into one big string |
| 46 | + const html = matchArray.map((place) => { |
| 47 | + return ` |
| 48 | + <li> |
| 49 | + <span class='name'>${place.city}, ${place.state}</span> |
| 50 | + <span class='population'>${place.population}</span> |
| 51 | + </li> |
| 52 | + `; |
| 53 | + }).join(''); |
| 54 | + suggestions.innerHTML = html; |
| 55 | +}; |
| 56 | + |
| 57 | +const searchInput = document.querySelector('.search'); |
| 58 | +const suggestions = document.querySelector('.suggestions'); |
| 59 | + |
| 60 | +// evertime a word is entered |
| 61 | +searchInput.addEventListener('change', displayMatches); |
| 62 | +// fire evertime a key is pressed |
| 63 | +searchInput.addEventListener('keyup', displayMatches); |
| 64 | + |
36 | 65 |
|
37 | | - // g means we will do a global search via the regex and i means case incensitive |
38 | | - const regex = new RegExp(wordToMatch, 'gi'); |
39 | | - return place.city.match(regex) || place.state.match(regex); |
40 | | - }); |
41 | | - } |
42 | 66 | </script> |
43 | 67 | </body> |
44 | 68 | </html> |
0 commit comments