skip to Main Content

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

Answers


  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.

    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
  3. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search