简体   繁体   中英

Check if two URL strings are equal

I'm building out a function to handle dynamic phone number swapping, identifying the referral url, mapping through a data set, and then outputting the promoUrl 's related phone number. The data is formatted like this:

const phoneNumbers = [
  {
    promoUrl: '/interior-doors/',
    promoNumber: '589-918-0710',
  },
  {
    promoUrl: '/promo4/',
    promoNumber: '307-789-8615',
  },
];

And the function maps through the data and reduces it, allowing me to sort through it like this:

const url = location.pathname.replace(/\/+$/, '');

const promoNumber = phoneNumbers.reduce((promoNumber, results) => {
  const hasPromo = results.promoUrl.includes(url);

  if (hasPromo) {
    return results.promoNumber;
  }
    return promoNumber;
}, '');

I'm having some issues with hasPromo . The way it's built right now allows for the promoUrl to have some variance and still work, meaning as long as it includes what is returned from url then it works ie /interior-doors/ , /interior-doors , and interior-doors will all work, which is great, but it also works if url is /interior-do . I need it to not do that. It should work independent of formatting, but only return the promoNumber if the string of letters is exact.

I'm assuming this is a regex thing, but I don't know what I'm doing with regex . Any help would be greatly appreciated.

Use == to do an exact match. And since the promoURL property always has / around it, add those delimiters when you set url

const url = '/' + location.pathname.replace(/\/+$/, '') + '/';

const promoNumber = phoneNumbers.reduce((promoNumber, results) => {
  const hasPromo = results.promoUrl == url;

  if (hasPromo) {
    return results.promoNumber;
  }
  return promoNumber;
}, '');

reduce also seems like the wrong function for this. You just need to find the matching promoUrl , you don't have to continue reducing, since the reduction function doesn't merge the results in any way.

const promo = phoneNumbers.find(({promoUrl}) => promoUrl == url);
const promoNumber = promo ? promo.promoNumber : '';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM