Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 8 additions & 4 deletions 06 - Type Ahead/index-FINISHED.html
Original file line number Diff line number Diff line change
Expand Up @@ -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)
});
}
Expand All @@ -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, `<span class="hl">${this.value}</span>`);
const stateName = place.state.replace(regex, `<span class="hl">${this.value}</span>`);
const regex = new RegExp("(" + escapeRegExp(this.value) + ")", 'gi');
const cityName = place.city.replace(regex, `<span class="hl">$1</span>`);
const stateName = place.state.replace(regex, `<span class="hl">$1</span>`);
return `
<li>
<span class="name">${cityName}, ${stateName}</span>
Expand Down