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
Fixing regexes
Putting unescaped user input into regex is a bad idea #1 - for example, typing . into search field will create weird result
Replacing substring with a user input is a bad idea #2 - it's not respecting letter case
  • Loading branch information
shushpanchik authored Sep 18, 2017
commit 67cf4f09ff91826d91ff6349731a67f44619c518
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