Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

Custom JavaScript URL Builder

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());
Comment

PREVIOUS NEXT
Code Example
Javascript :: js append zeros 
Javascript :: how to run node js with proxy 
Javascript :: max method in js 
Javascript :: react-dropzone 
Javascript :: date to string format javascript 
Javascript :: how to give icon in input type file react 
Javascript :: discord.js if arguments null 
Javascript :: how to cast in javascript 
Javascript :: AJAX JAVASCRIPT FUNCTION CALLS 
Javascript :: js byte size 
Javascript :: mongodb add 1 to field 
Javascript :: import all images from folder react 
Javascript :: how to create an array in javascript 
Javascript :: queryselectors select element whole class 
Javascript :: create a pdf puppeteer js 
Javascript :: clone an object in javascript 
Javascript :: json to csv javascript 
Javascript :: pause console debugger in react 
Javascript :: greater than x but less than y javascript 
Javascript :: compare date javascript 
Javascript :: start live server react js 
Javascript :: push javascript 
Javascript :: how to make a circle in p5js 
Javascript :: nuxtjs loading 
Javascript :: object promise javascript 
Javascript :: Parse BSON to JSON 
Javascript :: redux devtools config 
Javascript :: Creating with the custom hook in react 
Javascript :: javascript clone element 
Javascript :: sum of two array in javascript 
ADD CONTENT
Topic
Content
Source link
Name
7+3 =