提供一個城市的資料庫,並建立一個input,每輸入一個字元都要撈取資料,並做與城市的資料庫做模糊比對,將結果列出
fetch資料,並將資料暫存在瀏覽器,並透過JSON解析出檔案內容const endpoint = 'https://gist.githubusercontent.com/Miserlou/c5cd8364bf9b2420bb29/raw/2bf258763cdddd704f8ffd3ea9a3e81d25e2c6f6/cities.json'; const cities = []; fetch(endpoint) .then(blob => blob.json()) .then(data => cities.push(...data));建立模糊比對方法,使用正則表示式,
g代表global,i代表insensitivefunction findMatch(worldToMatch, cities) { return cities.filter(place => { const regex = new RegExp(worldToMatch, 'gi'); return place.city.match(regex) || place.state.match(regex); }); }建立監聽方法,監聽input,在
change、keyup時做搜尋searchInput.addEventListener('change', displayMatches); searchInput.addEventListener('keyup', displayMatches);change事件只會在離開element後觸發
將搜尋到的結果渲染上下拉選單中
function displayMatches() { const findArray = findMatch(this.value, cities); const html = findArray.map(place => { return ` <li> <span class='name'>${place.city}, ${place.state} </span> <span class='population'>${place.population}</span> </li> ` }).join(''); suggestions.innerHTML = html }將比對到的字元hightlight
const regex = new RegExp(this.value, 'gi'); const cityName = place.city.replace(regex, `<span class='hl'>${this.value}</span>`); const stateName = place.state.replace(regex, `<span class='hl'>${this.value}</span>`);
知識點
- HTML5提供了
fetch方法,可以直接取的API回傳的資料,回傳的資料是Promise,需要用then來接 - Blob (Binary Large Object) 是一種數據類型,通常用於存储二進制數據,如圖像、音頻和影片文件,或者其他任何二進制數據。它是一種包含任意數據的數據結構,没有特定的文件格式或編碼規則。
const regex = new RegExp(this.value, 'gi');,提供模糊比對Array.join()可以將陣列轉換成長字串
![[Release Notes] 20220325_v1 - Support Paypal & Patreon Donation button](https://static.coderbridge.com/images/covers/default-post-cover-1.jpg)
![[BE201] 後端中階:簡單會員註冊系統](https://static.coderbridge.com/images/covers/default-post-cover-2.jpg)

