const location = ['Bradenton', 'Broward', 'Miami', 'Orlando', 'Palm Beach'];
var url = '?_dFR[location_page][0]=Miami&_dFR[location_page][1]=Orlando&_dFR[make][0]=Acura&_dFR[make][1]=Audi&_dFR[make][2]=BMW&_dFR';
As you see url
have Miami and Orlando that have in location
.
The result should be: ['Miami', 'Orlando']. I tried to use regex but it is too complex. Is there an easier way?
CodePudding user response:
const locations = ['Bradenton', 'Broward', 'Miami', 'Orlando', 'Palm Beach'];
var url = '?_dFR[location_page][0]=Miami&_dFR[location_page][1]=Orlando&_dFR[make][0]=Acura&_dFR[make][1]=Audi&_dFR[make][2]=BMW&_dFR';
const foundLocs=locations.filter(l=>url.includes(l))
console.log(foundLocs);
CodePudding user response:
I think you're looking for filter
const locationList = ['Bradenton', 'Broward', 'Miami', 'Orlando', 'Palm Beach'];
const url = '?_dFR[location_page][0]=Miami&_dFR[location_page][1]=Orlando&_dFR[make][0]=Acura&_dFR[make][1]=Audi&_dFR[make][2]=BMW&_dFR';
const results = locationList.filter(currentLocation => url.includes(currentLocation));
console.log(results);
You also can use toLowerCase()
and toUpperCase()
to ignore case sensitive for your matches
const locationList = ['Bradenton', 'Broward', 'Miami', 'Orlando', 'Palm Beach'];
//lowercase for `orlando` and uppercase for `MIAMI`
const url = '?_dFR[location_page][0]=MIAMI&_dFR[location_page][1]=orlando&_dFR[make][0]=Acura&_dFR[make][1]=Audi&_dFR[make][2]=BMW&_dFR';
const results = locationList.filter(currentLocation => (url.includes(currentLocation.toLowerCase()) || url.includes(currentLocation) || url.includes(currentLocation.toUpperCase())));
console.log(results);
Regex version
const locationList = ['Bradenton', 'Broward', 'Miami', 'Orlando', 'Palm Beach'];
//lowercase for `orlando` and uppercase for `MIAMI`
const url = '?_dFR[location_page][0]=MIAMI&_dFR[location_page][1]=orlando&_dFR[make][0]=Acura&_dFR[make][1]=Audi&_dFR[make][2]=BMW&_dFR';
const results = locationList.filter(currentLocation => new RegExp(currentLocation, 'i').exec(url));
console.log(results);