From 67cf4f09ff91826d91ff6349731a67f44619c518 Mon Sep 17 00:00:00 2001 From: shushpanchik Date: Mon, 18 Sep 2017 22:59:32 +1000 Subject: [PATCH] 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 --- 06 - Type Ahead/index-FINISHED.html | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) 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}