diff --git a/06 - Type Ahead/index-FINISHED.html b/06 - Type Ahead/index-FINISHED.html index 5902b43936..a9a8df98a6 100644 --- a/06 - Type Ahead/index-FINISHED.html +++ b/06 - Type Ahead/index-FINISHED.html @@ -22,10 +22,14 @@ .then(blob => blob.json()) .then(data => cities.push(...data)); +function escapeRegExp(str) { + return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"); +} + function findMatches(wordToMatch, cities) { return cities.filter(place => { // here we need to figure out if the city or state matches what was searched - const regex = new RegExp(wordToMatch, 'gi'); + const regex = new RegExp(escapeRegExp(wordToMatch), 'gi'); return place.city.match(regex) || place.state.match(regex) }); } @@ -37,9 +41,9 @@ function displayMatches() { const matchArray = findMatches(this.value, cities); const html = matchArray.map(place => { - const regex = new RegExp(this.value, 'gi'); - const cityName = place.city.replace(regex, `${this.value}`); - const stateName = place.state.replace(regex, `${this.value}`); + const regex = new RegExp("(" + escapeRegExp(this.value) + ")", 'gi'); + const cityName = place.city.replace(regex, `$1`); + const stateName = place.state.replace(regex, `$1`); return `
  • ${cityName}, ${stateName}