JavaScript URL Builder – Build an URL and its Search Parameters

In this article, we will see how to build an URL and its search parameters and how to create a custom JavaScript URL builder.

Getting to know the URL API

Regular expressions are widely used to validate and create URLs in JavaScript, and for good cause. However, the URL API proves useful whenever I need to create one. It’s worth noting that it doesn’t work on Internet Explorer, but it does in modern browsers and Node.js.

It comes with URL validation and a nice API for working with search parameters out of the box. To create an URL call the constructor like so:

const myUrl = new URL("https://www.softhunt.net");

You could wonder where the proof is. You won’t have to worry because you’ll be notified if the argument is invalid: Like as you see in the below code.

const myUrl = new URL("www.softhunt.net");

Result:

 JavaScript URL Builder error

What constitutes a valid URL in the context of the URL API? Because a URL must include at least the host and protocol, even if it lacks the extension, the following example is formally valid:

const anotherUrl = new URL("https://w");

If you are unaware of how to parse URLs then I must recommend you to read our last article on how to parse url.

While the URL API is useful, you may still require substantial extension checking (a Proxy could do). In any case, there is also support for the hash part:

const anotherUrl = new URL("https://w.com/#about");
console.log(anotherUrl.hash);

Result:

 JavaScript URL Builder hash

The URL API, on the other hand, shines when it comes to creating search parameters. So let’s see in the next section.

How to build an javascript URL and its search parameters

Suppose you want to build an  URL: https://www.softhunt.net/?city=Karachi&price=$200k. The parts?city=Karachi&price=$200k in this example are search parameters, or query parameters, which are helpful whenever you need to submit a query to the backend.

JavaScript template literals would be used in a basic way to construct the URL:

const city = "Karachi";
const price = "$200k";

const myUrl = `https://www.softhunt.net/?city=${city}&price=${price}`;
console.log(myUrl);

Output:

URL Build img

However, this attack strategy will quickly fall apart, resulting in confusing code. Fortunately, the URL API has a property that allows you to interact with search parameters. Take a look at this:

const myUrlWithParams = new URL("https://www.softhunt.net/");

myUrlWithParams.searchParams.append("city", "Karachi");
myUrlWithParams.searchParams.append("price", "$200k");

console.log(myUrlWithParams.href);

Output:

URL Build img

That is how a correct URL is created. You can still change the original URL even if myUrlWithParams.searchParams is marked as read-only. In this case, searchParams is a URLSearchParams object with an append function for adding additional search parameters.

Now you have learned how to build URL but problem is that we have to combine parameters each time we write code. So here is the solution to this in the next section.

Custom JavaScript URL Builder

When performing operations on URLs, it is inconvenient to have to write code that encodes and mixes arguments each time; the answer is to utilize the URL class or develop your own simple custom class, as shown in the example below.

function UrlBuilder(prefix) {
  let cache = null;
  const parameters = {};
  this.getParameter = function(name, defaultValue) {
    return parameters[name] ?? defaultValue;
  };
this.setParameter = function(name, value) {
      const parameter = parameters[name];
      if (parameter === value) {
          return;
      }
      cache = null;
      if (value == null) {
          delete parameters[name];
      } else {
          parameters[name] = String(value);
      }
  };
  this.toString = function() {
    if (cache === null) {
        let url = '';
          const entries = Object.entries(parameters);
          for (const entry of entries) {
              const name = encodeURIComponent(entry[0]);
              const value = encodeURIComponent(entry[1]);
              url += (url ? '&' : '?') + name + '=' + value;
          }
          cache = prefix + url; 
      }
      return cache;
  };
}

// Usage example:

const builder = new UrlBuilder('https://softhunt.net/page');

builder.setParameter('preview', true);
builder.setParameter('admin', 'ranjeet');
builder.setParameter('age', 22);

console.log(builder.toString()); 

builder.setParameter('preview', null);
builder.setParameter('admin', null);

console.log(builder.toString()); 

Output:

URL result

Conclusion

The URL API is a simple JavaScript interface for creating and verifying URLs. It works with Node.js and most modern browsers.

Although it does not enforce the TLD (top-level domain), the URL API provides the first layer of validation for URLs. Still, it’s a useful tool for automating the creation of search parameters and processing URLs in JavaScript.

That’s all for this article if you have any confusion contact us through our website or email us at [email protected] or by using LinkedIn

Suggested Articles:

  1. What is the Callback Function in JavaScript?
  2. How to Get URL Parameters with JavaScript [With Examples]
  3. JavaScript URL Parse with parse-url

Leave a Comment