Home > Net >  figure out the structure difference of 2 urls in javascript
figure out the structure difference of 2 urls in javascript

Time:09-16

Given the two URLs below, I need to be able to tell which structure the url is in (either url1 structure or url2 structure) and then parse out both random strings. The domain name will be different each time so I can't hardcode in any specific domain name

url1 is in the form of domainname.com/q/{random-6-character-alphanumeric-string}?arg1=something&arg2=something

url2 is in the form of domainname.com/q/{random-6-character-alphanumeric-string}/{random-3-character-alphanumeric-string}?arg1=something&arg2=something

So for example, let's say:

url1 = mydomain.com/q/abc1de?arg1=something&arg2=something
url2 = mydomain.com/q/abc1de/b78?arg1=something&arg2=something

I tried just parsing url1 and was able to figure out parsedText1 = url.substring(url.lastIndexOf("/") 1).split("?")[0]

The problem is this does not work for url2 and I can't figure out how to write the code to distinguish between the two structures. How do I figure out which structure the url is in and then parse out the random strings accordingly?

CodePudding user response:

Maybe using URL.pathname works for you?

const a = new URL(`http://domainname.com/q/a2qwer?something=1&anything=2`);
const b = new URL(`http://domainname.com/q/a2qwer/re2?something=1&anything=2`);
console.log(a.pathname);
console.log(b.pathname);

  • Related