Jesse Winton
Jesse Winton

Reputation: 706

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 i.e. /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.

Upvotes: 0

Views: 1195

Answers (1)

Barmar
Barmar

Reputation: 781592

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 : '';

Upvotes: 2

Related Questions