-2

I need to run a function on a URL that doesn't contain subdirectories - one that only applies to the root domain, but where the root domain can have query string.

For example, this should match:

  • domain.com
  • domain.com?utm=blah
  • domain.com/?utm=blah

It shouldn't match:

  • domain.com/directory

(I can't just check for a / since that's technically included in even a URL on the root domain.)

I imagine I can get fancy with splitting the URL and all, but wondering if there's an easier way to say, "If the URL after '.com/' either doesn't exist or doesn't start with ?"...

3 Answers3

1

You can parse the URLs with the URL class and extract the pathname property. If the pathname is longer than "/", then it has a non-empty path

const urls = [
  "https://example.com",
  "https://example.com?utm=blah",
  "https://example.com/?utm=blah",
  "https://example.com/index.html?utm=blah",
  "https://example.com/directory"
];

urls.forEach((url) => {
  const parsed = new URL(url);
  const hasPath = parsed.pathname.length > 1;
  console.log(url, "has path:", hasPath);
});

Note, this produces false positives for URLs with PATH_INFO, eg https://example.com/index.html/foo/bar/baz but it's not clear if you need that level of support.

Phil
  • 157,677
  • 23
  • 242
  • 245
0

I think you want

window.location.pathname === '/'

pathname will be / if you're at https://www.google.com, but it'll be /search if you're at https://www.google.com/search?q=foo

mpen
  • 272,448
  • 266
  • 850
  • 1,236
-1

I believe the solution can be found at the following fine URL: https://stackoverflow.com/a/42353290/1132976

Basically, check to see if window.location.search is a valid object. There is discussion on how to iterate on the values within the object at that article.

PS: This probably won't work on really old browsers. YMMV.

uotonyh
  • 786
  • 5
  • 7
  • 1
    `search` is the query string. I think OP is talking about the path. "valid object" is weird verbiage. It's a string. It'll either be an empty string, or contain the part after and including `?` – mpen Jan 06 '23 at 01:43
  • The link in the answer shows using the `window.location.search` in the constructor of a `URLSearchParams` object. The example provided allows for a great deal of flexibility in parsing the query string, even though the OP might not need that. – uotonyh Jan 09 '23 at 18:23