Search code examples
javascripturl

constructing url with base url strips the path in base url


When I try to construct a url in JavaScript using new URL(url, base), it strips the pathname in base

below is my code

const getUrl = () => {
  const ids = ["1","2","3"];
  const url = new URL("/items", "https://example.com/v1");
  url.searchParams.set("id", ids?.toString() ?? "");
  
  return url.toString();
};

console.log(getUrl());
// https://example.com/items?id=1%2C2%2C3

I need the output to be: https://example.com/v1/items?id=1%2C2%2C3


Solution

    1. You can't prefix a relative path with / or it will be relative to the domain name.
    2. You can't omit / after the base url or the last segment will be replaced by the relative path.

    Solution:

    1. Remove leading slash from /items --> items
    2. Add trailing slash after the base url --> .../v1/

    const getUrl = () => {
      const ids = ["1","2","3"];
      const url = new URL("items", "https://example.com/v1/");
      url.searchParams.set("id", ids?.toString() ?? "");
      
      return url.toString();
    };
    
    console.log(getUrl());