JS 30 Lesson 6 : fetch, Event, RegExp, map, join - innowantai/Note GitHub Wiki

This lesson will make a search-engine that can real time show the search results

Fully Code of the Lesson 6

const endpoint = 'https://gist.githubusercontent.com/Miserlou/c5cd8364bf9b2420bb29/raw/2bf258763cdddd704f8ffd3ea9a3e81d25e2c6f6/cities.json';


let cities = null

fetch(endpoint).then(function (res) { 
  res.json().then(function (obj) {
    cities = obj  
  });
})

document.querySelector('.search').addEventListener('keyup',function () { 
  let filter = this.value
  let regexp = new RegExp(filter,'gi') 
  let filterAry = cities.filter(function (city) {  
    return city.city.match(regexp) || city.state.match(regexp)
  })
 
 
  let html = filterAry.map(function (city) { 
    let cityName = city.city.replace(regexp,`<span class = "h1">${filter}</span>`)
    let stateName = city.state.replace(regexp,`<span class = "h1">${filter}</span>`)
    return `
        <li>
          <span class = 'name'>${cityName}, ${stateName} </span>
          <span class = 'population'>${Number(city.population).toLocaleString()} </span>  
          //<span class = 'population'>${(city.population*1).toLocaleString()} </span>  
        </li> 
    `;

  }).join('') 
   
  document.querySelector('.suggestions').innerHTML = html
})

Step 1 : Loaging JSON data from URL by the API of fetch

When want to get data from URL that formation is JSON can follwing below code :

const endpoint = https://gist.githubusercontent.com/Miserlou/c5cd8364bf9b2420bb29/raw/2bf258763cdddd704f8ffd3ea9a3e81d25e2c6f6/cities.json


let cities = null
fetch(endpoint).then(function (res) { 
  res.json().then(function (obj) {
    cities = obj  
  });
})

Step 2 : Listen and Trigger the event

We have a block of the form that include input label

  <form class="search-form">
    <input type="text" class="search" placeholder="City or State">
    <ul class="suggestions">
      <li>Filter for a city</li>
      <li>or a state</li>
    </ul>
  </form>

In the JS that often used triggle of event is click,keyup and keydown,
so when we want to listen the event of the input box that have several choice

function Trigger(){}
1. document.querySelector('.search').addEventListener('keyup',Trigger)
2. document.querySelector('.search').addEventListener('keydown',Trigger)
3. document.querySelector('.search').addEventListener('change',Trigger)
  • Case 1 : keyup
    • It's not real time to detect the event that have several delay
  • Case 2 : keydown
    • It's real time to detect but have the problem of repeat trigger that need to another process
  • Case 3 : change
    • It detected when change the browser window or KEY press Enter, so that is not sensitive to detect the event

In this Lesson the Case 1 of keyup is the best choice

Step 3 : Using RegExp to filter input String

First, Buliding the RegExp formulation by the object of RegExp -> let regexp = new RegExp(filter,'gi')
The parameters of the RegExp's object filter and gi that means filter-string and filter-rule respectively,

  • The g is global search of filter-string that mean is search from head to end
  • The i is immaterial search similar blur that mean is not recognize Upper and Lower of the letter
  • The method of RegExp of match(regexp) is return true or false

Filter all data from the variable of cities by the method of filter and the RegExp method of match that results are saving into the variable of filterAry

  let filter = this.value
  let regexp = new RegExp(filter,'gi') 
  let filterAry = cities.filter(function (city) {  
    return city.city.match(regexp) || city.state.match(regexp)
  })

Step 4 : After filter target string, using the method of map to combine HTML Array

Combining the purpose HTML from the filterAry by the method of map

  • The method of map is to map new array desired and using the method of join to transfer to fully string
  • The method of RegExp of the replace(regexp,string) is to replace regexp to string
  • The population of the city is the string type, and using Number(string) or (sting*1) to transfer to number
  • For filter = los example, the population is 3884307 and using the method of toLocaleString to transfer to 3,884,307 formulation
  let html = filterAry.map(function (city) { 
    let cityName = city.city.replace(regexp,`<span class = "h1">${filter}</span>`)
    let stateName = city.state.replace(regexp,`<span class = "h1">${filter}</span>`)
    return `
        <li>
          <span class = 'name'>${cityName}, ${stateName} </span>
          <span class = 'population'>${Number(city.population).toLocaleString()} </span>  
          //<span class = 'population'>${(city.population*1).toLocaleString()} </span>  
        </li> 
    `;

  }).join('') 

⚠️ **GitHub.com Fallback** ⚠️