Search code examples
javascripturlquery-stringlocation-href

URL from location.href missing searchParams


I'm trying to parse the query/search parameters of the current route

let url = new URL(location.href);

When I look at url the search parameters are in href. I expected them to be in searchParams, which is empty. Are my expectations off?

URL:

hash: "#/admin?ac=flags"
host: "localhost:8084"
hostname: "localhost"
href: "http://localhost:8084/#/admin?ac=flags"
origin: "http://localhost:8084"
password: ""
pathname: "/"
port: "8084"
protocol: "http:"
search: ""
searchParams: URLSearchParams { }


Solution

  • href contains the whole URL

    The query string will appear in searchParams but your URL doesn't have a query string.

    You have a fragment identifier (the section starting with #) which is the last component of the URL.

    If you were to have a query string, you need a section starting with ? after the path but before the fragment identifier.