Languages
[Edit]
EN

JavaScript - own url builder

3 points
Created by:
Root-ssh
94100

In this short article we would like to show how to create custom URL builder in JavaScript.

It is problematic when we make some operations on URLs that each time force us to write some code which encodes and combines parameters togather - the solution is to use URL class or write own simple custom class what was presented in below example.

Note: to see TypeScript version go to this article.

Practical example:

// ONLINE-RUNNER:browser;

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://domain.com/page');
  
builder.setParameter('preview', true);
builder.setParameter('user', 'john');
builder.setParameter('age', 20);

console.log(builder.toString()); // https://domain.com/page?preview=true&user=john&age=20

builder.setParameter('preview', null);
builder.setParameter('user', null);
  
console.log(builder.toString()); // https://domain.com/page?age=20
Native Advertising
­čÜÇ
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

ÔŁĄ´ŞĆ­čĺ╗ ­čÖé

Join