mentalo
mentalo

Reputation: 134

Match a URL with placeholders with a URL with filled placeholders

I am trying to match two URLs, one with placeholders and one with filled placeholders in Angular with TypeScript.

For Example

URL before the placeholders are filled:

http://this/is/{placeholder1}/{placeholder2}/my/url?limit=10&offset=5

URL after the placeholders are filled:

http://this/is/100Banana/200Apple/my/url?limit=10&offset=5

The target is to match those two URLs with Regex and get a match. One of the problems is, that the placeholders could be filled with anything a URL allows.

The first attemp was to replace the placeholders with Regex like [^/]+ before the Regex match. But that only works if the placeholders were at the end of the URL.

Upvotes: 1

Views: 883

Answers (1)

Matus Dubrava
Matus Dubrava

Reputation: 14462

If you just need to match them then you don't need a regex. You can do it like this.

const str1 = 'http://this/is/{placeholder1}/{placeholder2}/my/url?limit=10&offset=5';
const str2 = 'http://this/is/100Banana/200Apple/my/url?limit=10&offset=5';

// url1: url with placeholders
// url2: url with filled placeholders
const compareUrls = (url1, url2) => {
  const u1 = url1.split('/');
  const u2 = url2.split('/');

  if (u1.length !== u2.length) { return false; }

  for (let i = 0; i < u1.length; i++) {
    if (u1[i].startsWith('{placeholder')) { continue; }
    if (u1[i] !== u2[i]) { return false; }
  }
  return true;
};

console.log(compareUrls(str1, str2));

Upvotes: 2

Related Questions